Interesting Java statement issues

The question arises:

Why in this case do I get a compilation error in Java?

byte x = 0; x = 128; 

But this is legal:

 x+= 999l; 

I am using eclipse, jdk 7.

thanks

+6
source share
4 answers

In the first:

 byte x = 0; x = 128; 

A byte is a signed integral type with a width of 8 bits and can express a range from -128 to +127 .

x = 128 means "assign x to 128 ", and by default 128 is of type int , so you are trying to assign int to byte , which can cause Possible loss of precision , because int wider than byte . To make this work, you need to explicitly specify a 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 are just overflowing the values.

 byte x = 0; x += 999L; // don't really need the long qualifier here // x is now -25. 
+2
source

byte signed and can only contain a maximum value of 127 and a minimum value of -128 , so the first case gives you a compilation error.

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

+4
source
Byte

has a range from -128 to 127. This is x + = 999l; works because it is a complex assignment operator. look at the same or a similar question here .

+1
source

In this first statement, x = 128 , since the range of bytes 0-127 in java requires an explicit cast, and therefore a compilation error. In the second case, it overflows and converts to -25, which is in the byte range.

0
source

Source: https://habr.com/ru/post/915731/


All Articles