Automatic Type Promotion in Expressions

For example, examine the following expression:


public class Main {
  public static void main(String[] argv) {
    byte a = 40;
    byte b = 50;
    byte c = 100;
    int d = a * b / c;
  }
}

The result of a * b exceeds the range of byte. To handle this kind of problem, Java automatically promotes each byte or short operand to int. a * b is performed using integers.

Automatic promotions can cause compile-time errors.


public class Main {
  public static void main(String[] argv) {
    byte b = 5;
    b = b * 2; // Error! Cannot assign an int to a byte!
  }
}

Compiling the code above generates the following errors:


D:\>javac Main.java
Main.java:4: possible loss of precision
found   : int
required: byte
    b = b * 2; // Error! Cannot assign an int to a byte!
          ^
1 error

If you understand the consequences of overflow, use an explicit cast.


public class Main {
  public static void main(String[] argv) {
    byte b = 50;
    b = (byte) (b * 2);

    System.out.println("b is " + b);
  }
}

The output from the code above is:


b is 100
Home 
  Java Book 
    Language Basics  

Type Casting:
  1. Type Conversion and Casting
  2. Casting Incompatible Types
  3. Automatic Type Promotion in Expressions
  4. The Type Promotion Rules