Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Type promotion Java

Tags:

java

casting

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.

like image 819
Euriloco Avatar asked Dec 25 '22 17:12

Euriloco


1 Answers

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.

like image 97
yas Avatar answered Jan 05 '23 17:01

yas