Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java operators interesting issue

Tags:

java

operators

The question is:

Why in this case i get compilation error in Java?

byte x = 0;
x = 128;

But this is legal:

x+= 999l;

I use eclipse, jdk 7.

Thank You

like image 524
sidanmor Avatar asked May 14 '12 20:05

sidanmor


2 Answers

byte is signed and can only hold a maximum value of 127 and a minimum value of -128, that is why the first case gives you a compile error.

The second case compiles because and value you add to a 'byte' wraps around, notice that 999 % 128 = 103, which is in the valid range of a 'byte'

like image 118
Hunter McMillen Avatar answered Sep 24 '22 01:09

Hunter McMillen


In your first one:

byte x = 0;
x = 128;

A byte is a signed integral type, 8-bits wide, and can express the range of -128 to +127.

x = 128 means "assign x to 128", and by default, 128 is of type int, so you're trying to assign an int to byte which would cause Possible loss of precision errors, because int is wider than byte. To get this to work, you would have to explicitly cast the value of 128.

byte x = 0;
x = (byte)128; // x is now -128.

For your second example, adding values to x is fine, but you just overflow the values.

byte x = 0;
x += 999L; // don't really need the long qualifier here
// x is now -25.
like image 36
逆さま Avatar answered Sep 23 '22 01:09

逆さま