简体   繁体   中英

Type promotion Java

I`m learning Java with the Herbert Schildt book's: Java a Beginner's Guide. In that book appears this code:

// A promotion surprise!
class PromDemo{
    public static void main(String args[]){
        byte b;
        int i;
        b = 10;
        i = b * b;      // OK, no cast needed

        b = 10;
        b = (byte) (b * b);     // cast needed!!

        System.out.println("i and b: " + i + " " + b);
    }
}

I don't understand why I must use (byte) in the line:

b = (byte) (b * b);     // cast needed!!

b was defined as a byte and the result of b * b is 100 which is right value for a byte (-128...127).

Thank you.

The JLS ( 5.6.2. Binary Numeric Promotion ) gives rules about combining numeric types with a binary operator, such as the multiplication operator ( * ):

  • If either of the operands is of type double, the other one will be converted to a double.
  • Otherwise, if either of the operands is of type float, the other one will be converted to a float.
  • Otherwise, if either of the operands is of type long, the other one will be converted to a long.
  • Otherwise, both operands will be converted to an int.

The last point applies to your situation, the bytes are converted to ints and then multiplied.

In Java, byte and short will always be promoted to int, when you have a calculation like this:

byte b = 10;
b = (byte) (b * b);

So you actually multiply an integer with an integer, which will return an integer. Since you cannot assign an integer to a byte, you need the cast.

This is called "automatic type promotion" if you would like to Google it (to find eg https://docs.oracle.com/javase/specs/jls/se7/html/jls-5.html#jls-5.6.2 )

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM