Does numeric promotion apply to constants in Java?

SMUsamaShah :

§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.

Michael :

Promotion necessarily must be done by the compiler because there are no JVM instructions for addition of shorts.

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.

Guess you like

Origin http://10.200.1.11:23101/article/api/json?id=467090&siteId=1