Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Does numeric promotion apply to constants in Java? [duplicate]

Tags:

java

constants

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

like image 851
SMUsamaShah Avatar asked May 02 '18 10:05

SMUsamaShah


1 Answers

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.

like image 96
Michael Avatar answered Sep 19 '22 13:09

Michael