6

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

3
  • 1
    Off to find the duplicate. The answer is: Compiler-time constant expressions. May 2, 2018 at 10:34
  • this should work short s = (short) (a + b); without final in a and b May 2, 2018 at 10:34
  • @T.J.Crowder It is different because I am asking about numeric promotion. Linked question is asking directly about casting. May 2, 2018 at 10:43

1 Answer 1

4

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.

0

Not the answer you're looking for? Browse other questions tagged or ask your own question.