Cannot assign 128 to byte, why does it error out instead of overflowing?

Viewed 1138

Bytes in Java range from -128 to 127. If over 127 they overflow. So I assigned 128 to a byte variable to know how overflow work, but the compiler shows a error message: "Type mismatch: cannot convert from int to byte".

Why do I get a compiler error instead of it overflowing?

enter image description here

4 Answers

javac will let you assign values within range to bytes. When you go out of range, the value needs to be explicitly cast.

byte b = (byte)128; 

Would work with the compiler. To see overflow you might try

byte b = 127;
b += 1;
System.out.println(b);

-128

The nuts and bolts can be found in the JLS. Java will do arithmetic as int, or long.

byte a = 1;
byte b = 2;
//byte c = a + b; //fails because the operation is performed as an int.
byte c = (byte)(a + b);

A byte is an 8-bit signed integer value that can hold values between -128 and 127.

You can cast 128 into a byte 'byte b = (byte)128;', but then b will just equal -128 because of how twos-complement numbers work.

Integer constants like 1, -32, 128, or 7654321 have int type in Java. Assigning an int value to a byte variable is simply not allowed. This is why you get the error cannot convert from int to byte. To get around it, you have to convert the int value to byte with a type cast, b=(byte)128.

The real question should be, why do you not get an error for this code?

byte b = 100; // !!!! ASSIGNING int TO byte !!!!

You don't get an error here because of this a special "assignment conversion" rule that only applies for compile time constant expressions:

A narrowing primitive conversion may be used if the type of the variable is byte, short, or char, and the value of the constant expression is representable in the type of the variable.

Type byte B = (byte)128;

instead of byte B = 128;

Related