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
java2s.com  |  | Contact Us | Privacy Policy
Copyright 2009 - 12 Demo Source and Support. All rights reserved.
All other trademarks are property of their respective owners.