OCA Java SE 8 Operators/Statements - Numeric Promotion








Numeric Promotion

Java uses the following Numeric Promotion Rules when applying operators to data types:

  • If two values have different data types, Java promotes one of the values to the larger of the two data types.
  • If one of the values is integral and the other is floating-point, Java promotes the integral value to the floating-point value's data type.
  • Smaller data types(byte, short, and char) are promoted to int any time they're used with a Java binary arithmetic operator, even if neither of the operands is int.
  • The resulting value will have the same data type as its promoted operands.

For the third rule, unary operators are excluded from this rule.

For example, applying ++ to a short value results in a short value.





Example

What is the data type of x * y?

     int x = 1; 
     long y = 2; 

Follow the first rule.

Since one of the values is long and the other is int, and long is larger than int, then the int value is promoted to a long, and the resulting value is long.

Example 2

What is the data type of x + y?

     double x = 3.21; 
      float y = 2.1; 

double? Wrong! This code will not compile! The floating-point literals are assumed to be double, unless postfixed with an f.

We can rewrite the code as

     double x = 3.21; 
      float y = 2.1f; 

If the value was to 2.1f, then the promotion with both operands being promoted to a double, and the result would be a double value.





Example 3

What is the data type of x / y?

     short x = 10; 
     short y = 3; 

Follow the third rule, namely that x and y will both be promoted to int before the operation, resulting in an output of type int.

The result is not double.

public class Main {
  static public void main(String[] argv) throws Exception {

    short x = 10;
    short y = 3;

    System.out.println(x / y);
  }
}

The code above generates the following result.

Example 4

What is the data type of x * y / z?

     short x = 4; 
     float y = 3; 
    double z = 3; 

For the first rule, x will be promoted to int because it is a short and it is being used in an arithmetic binary operation.

The promoted x value will then be promoted to a float so that it can be multiplied with y.

The result of x * y will then be automatically promoted to a double, so that it can be multiplied with z, resulting in a double value.