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