Java Numeric promotion

           Today I learned one more thing in Java, about the Numeric promotion and I though I should share it with my readers. Here’s my code :


The first part works fine, because we are adding final variables, addition of final variables are performed at compile time. And the result gets stored to the byte.

As per the Java Language Specification (JLS)

  “In addition, 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

Now the part 2 of the program :

We get the compile time error “Type mismatch : cannot convert from int to byte”. But where did we declare the int variable. It is because there is no + (addition) for byte, we cannot perform addition on byte type so it becomes 

byte=int + int;

The issue is narrowing conversion cannot be performed automatically by java runtime. We need to explicitly cast the value of byte to int. Here I want to add some rules given by JLS for conversion :

“When an operator applies binary numeric promotion to a pair of operands, each of which must denote a value that is convertible to a numeric type, the following rules apply, in order, using widening conversion (§5.1.2) to convert operands as necessary:

  • If any of the operands is of a reference type, unboxing conversion
    (§5.1.8) is performed. Then:
  • If either operand is of type double, the other is converted to double.
  • Otherwise, if either operand is of type float, the other is converted to
    float.
  • Otherwise, if either operand is of type long, the other is converted to
    long.
  • Otherwise, both operands are converted to type int.”

Please comment below if you have any questions or corrections .