Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Compilation error: casting

Tags:

java

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.

like image 571
Andrei Ciobanu Avatar asked Feb 16 '26 14:02

Andrei Ciobanu


1 Answers

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);
like image 83
Jesper Avatar answered Feb 18 '26 03:02

Jesper



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!