Compilation error: casting
You did it right by indicating that a cast is required, but unfortunately you did not apply it to the correct expression due to operator precedence.
Consider the following snippet:
static void f(char ch) {
System.out.println("f(char)");
}
static void f(int i) {
System.out.println("f(int)");
}
public static void main(String[] args) {
char ch = 'X';
f( (char) ch + 1 ); // prints "f(int)"
f( (char) (ch + 1) ); // prints "f(char)"
}
Listing takes precedence over padding, so the snippet prints what it does. That is, the first call is equivalent f( ((char) ch) + 1 );
. The result of the addition is int
, therefore, an overload is called f(int)
.
The lesson here is that you should always use brackets , unless you are doing a very basic cast. In general, always use parentheses to make the order of evaluation explicit, even if not needed. They lead to better, more readable code.
a source to share
Note that casting has a higher precedence than the + operator. Your code does this:
byte a = 50;
byte b = 40;
byte sum = ((byte)a) + b;
System.out.println(sum);
Listing is redundant, as it a
already exists byte
. You probably meant this:
byte a = 50;
byte b = 40;
byte sum = (byte) (a + b);
System.out.println(sum);
a source to share
Since the two byte variables are operands in +, they are implicitly promoted to int. This is called Numeric Promotion. Since int is larger than a byte and the result of a + b yields an int, discarding a byte is possibly discarding some bits, since int is larger than a byte. Hence, the "loss of precision"
Doc for implicit numerical advance:
http://java.sun.com/docs/books/jls/third_edition/html/conversions.html#170983
Doc for size types:
http://java.sun.com/docs/books/tutorial/java/nutsandbolts/datatypes.html