I am using Eclipse at the moment. Two things to note:
- The compiler checks the bounds during initialization.
- The compiler calculates the values โโof constant expressions, for example
3 * (2 + 1) .
It works:
byte b = 127;
But this is not so:
byte b = 128; // does not work, outside of range
It works:
byte b = 100 + -228;
But this is not so:
byte b = 1; byte c = b + 1;
And this is not so:
byte b = 1; byte c = b + (byte) 1;
Note that b is a variable expression. If a variable expression is involved, the result of the + operator is no less than int. Therefore, you cannot assign it c . Unlike constant expressions, the compiler does not evaluate variable expressions.
The compiler will also complain about short and char - try it yourself.
And finally, using final for a variable effectively turns it into a constant expression, so this will work:
final byte b = 1; byte c = b + 1;
Timbits
source share