Why can not I add two bytes and get an int and I can add two final bytes get a byte?

From the JLS 5.2 Assignment Conversion

In addition, if the expression is a constant expression (ยง15.28) of type byte, short, char, or int:
– 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.

In short the value of the expression (which is known at compile time, because it is a constant expression) is representable in the type of the variable that is byte.

Consider your expression

 final byte x = 1;
 final byte y = 2;
 byte z = x + y;//This is constant expression and value is known at compile time

So as summation fits into byte it does not raise an compilation error.

Now if you do

final byte x = 100;
final byte y = 100;
byte z = x + y;// Compilation error it no longer fits in byte

Leave a Comment