4

I'm reading java OCA certification documentation. Some primitive operations behavior seems realy strange for me.

it is said that all byte, short and char value are automatically widening to int when used as operand for arithmetic operations. this is perfectily logic. but confusion come when we make this operands final.

this code will not compile (logic)

 short s1 = 10 ;
 short s2 = 20 ;
 short sum = s1 + s2;

but this one will compile

  final short s1 = 10 ;
  final short s2 = 20 ;
  short sum = s1 + s2; 

Why this will compil successfuly? what property of the keyword final make this code compile?

soung
  • 1,411
  • 16
  • 33
  • 2
    *what property of the keyword final make this code compile?* **Nothing**. You are reaching a ***compiler*** optimization caused [constant folding](https://en.wikipedia.org/wiki/Constant_folding). – Elliott Frisch Jan 05 '20 at 13:10

1 Answers1

6

It makes s1 and s2 compile-time constant expressions, so the addition is done by the compiler, not at runtime, and the code is thus equivalent to

short sum = 30; 

The compiler is thus able to know that the value assigned to sum is small enough to fit into a short, and it thus compiles.

JB Nizet
  • 678,734
  • 91
  • 1,224
  • 1,255
  • done dear JB Niezet. But i was thinking the precision about data range was usefull. Nethermind i delete the anwser – soung Jan 05 '20 at 13:57
  • *The compiler is thus able to know that the value assigned to sum is small enough to fit into a short*. – JB Nizet Jan 05 '20 at 13:58