Why I need to use variable casting in this example?
byte b = -123;
b = (byte) ~b;
When I am trying to compile it without casting, I get:
NotDemo.java:17: error: possible loss of precision
Because with most Java operators (~ included), integer operands are promoted before the operator is applied. So byte is promoted to int; your code is equivalent to this:
b = (byte) ~((int) b);
Therefore in general, assigning back to a byte will lose information in the upper bits. (Although it's pretty meaningless in this case.)
Because ~b will convert/promote b to int before applying the ~.
Actually what invisibly happens is something like this.
~((int)b);
So the result is of type int.
And so you need the cast back to byte.
See the JLS for more details.
http://docs.oracle.com/javase/specs/jls/se7/html/jls-15.html#jls-15.15.5
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With