§5.1.2 and §5.6.2 do not mention how numeric promotion and widening work for constants.
The following gives an error as expected:
short a = 2;
short b = 3;
short s = a + b; // error: incompatible types: possible lossy conversion from int to short
But if they are declared final, it compiles without error:
final short a = 2;
final short b = 3;
short s = a + b; // no error
Why is that? And which section of the specs explains that?
My guess is that they are compile time constants and therefore treated as integers.
Promotion necessarily must be done by the compiler because there are no JVM instructions for addition of short
s.
However, the compiler is able to narrow the resulting integer sum to a short because:
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.
as described in the JLS.
Adding final
determines whether or not it's a constant expression.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With