Reputation: 253
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.
Upvotes: 4
Views: 398
Reputation: 3620
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.
Upvotes: 7
Reputation: 31605
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 e.g. https://docs.oracle.com/javase/specs/jls/se7/html/jls-5.html#jls-5.6.2)
Upvotes: 3