Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

byte casting when use NOT operator

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
like image 296
Karaal Avatar asked Mar 10 '26 14:03

Karaal


2 Answers

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.)

like image 164
Oliver Charlesworth Avatar answered Mar 12 '26 04:03

Oliver Charlesworth


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

like image 40
peter.petrov Avatar answered Mar 12 '26 04:03

peter.petrov