Why is "int i = 2147483647 + 1;" OK, but "byte b = 127 + 1;" is not compilable?

goku picture goku · Jul 31, 2011 · Viewed 7.2k times · Source

Why is int i = 2147483647 + 1; OK, but byte b = 127 + 1; is not compilable?

Answer

MByD picture MByD · Jul 31, 2011

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.