Reputation: 12838
Can somebody explain me why the following piece of code fails to compile. The error is: "Possible loss of precision.
" :
byte a = 50;
byte b = 40;
byte sum = (byte)a + b;
System.out.println(sum);
Thank you.
Upvotes: 2
Views: 151
Reputation: 383746
You did right by identifying that a cast is required, but unfortunately you did not apply it to the right expression due to precedence of operators.
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)"
}
The cast has a higher precedence than the addition, which is why the snippet prints what it does. That is, the first call is equivalent to f( ((char) ch) + 1 );
. The result of the addition is an int
, which is why the f(int)
overload is invoked.
The lesson here is that you should always use parenthesis unless you're doing a very simple cast. In general, always consider using parentheses to make the order of evaluation explicit, even if they're not necessary. They lead to a better, more readable code.
Upvotes: 1
Reputation: 206796
Note that the cast 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);
The cast is redundant, since a
is already a byte
. You probably meant this:
byte a = 50;
byte b = 40;
byte sum = (byte) (a + b);
System.out.println(sum);
Upvotes: 4
Reputation:
Because the two byte variables are operands to +, they are implicitly promoted to int. This is called Numeric Promotion. Because int is larger than byte, and the result of a + b yields int, casting to byte possibly chops off some bits, as int is larger than byte. Hence the "loss of precision"
Doc for implicit numeric promotion:
http://java.sun.com/docs/books/jls/third_edition/html/conversions.html#170983
Doc for the size of types:
http://java.sun.com/docs/books/tutorial/java/nutsandbolts/datatypes.html
Upvotes: 3
Reputation: 7388
Bytes are added using "int" arithmetic; thus the result is an int and must be cast back from int to byte, which leads to the possibility of truncation.
Upvotes: 1