Why is "int i = 2147483647 + 1;" OK, but "byte b = 127 + 1;" is not compilable?
Why is int i = 2147483647 + 1;
OK, but byte b = 127 + 1;
is not compilable?
Solution 1:
Constants are evaluated as ints, so 2147483647 + 1
overflows and gives you a new int, which is assignable to int
, while 127 + 1
also evaluated as int
equals to 128
, and it is not assignable to byte
.
Solution 2:
The literal 127 denotes a value of type int. So does the literal 1. The sum of these two is the integer 128. The problem, in the second case, is that you are assigning this to a variable of type byte. It has nothing to do with the actual value of the expressions. It has to do with Java not supporting coercions (*). You have to add a typecast
byte b = (byte)(127 + 1);
and then it compiles.
(*) at least not of the kind String-to-integer, float-to-Time, ... Java does support coercions if they are, in a sense, non-loss (Java calls this "widening").
And no, the word "coercion" did not need correcting. It was chosen very deliberately and correctly at that. From the closest source to hand (Wikipedia) : "In most languages, the word coercion is used to denote an implicit conversion, either during compilation or during run time." and "In computer science, type conversion, typecasting, and coercion are different ways of, implicitly or explicitly, changing an entity of one data type into another.".
Solution 3:
As an evidence to @MByD:
The following code compiles:
byte c = (byte)(127 + 1);
Because although expression (127 + 1)
is int and beyond the scope off byte
type the result is casted to byte
. This expression produces -128
.