Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Type promotion in Java [duplicate]

Tags:

java

I have a problem with the below Java statements:

byte b = 10;
byte r = (byte) (b * b); // Giving correct result
byte r = (byte) b * b; // Giving error " POSSIBLE LOSS OF PRECISION"

Why is it mandatory to give parentheses to b * b?

like image 254
praveen padala Avatar asked Jan 16 '19 08:01

praveen padala


3 Answers

(byte) b * b casts the value of the first b to byte (which is redundant since it was already byte), and multiples it by the value of the second b. Multiplying two bytes promotes them to int first, since there is no * operator for bytes. Therefore the result is int, and cannot be assigned to a byte variable.

On the other hand, (byte)(b * b) casts the int multiplication result to byte, which can be assigned to a byte variable.

This is covered in the JLS in 5.6.2. Binary Numeric Promotion:

When an operator applies binary numeric promotion to a pair of operands, each of which must denote a value that is convertible to a numeric type, the following rules apply, in order:

  1. If any operand is of a reference type, it is subjected to unboxing conversion (§5.1.8).

  2. Widening primitive conversion (§5.1.2) is applied to convert either or both operands as specified by the following rules:

    • If either operand is of type double, the other is converted to double.

    • Otherwise, if either operand is of type float, the other is converted to float.

    • Otherwise, if either operand is of type long, the other is converted to long.

    • Otherwise, both operands are converted to type int.

like image 186
Eran Avatar answered Nov 09 '22 02:11

Eran


Casting problem

byte r = (byte) (b * b);

It casts the (byte) type to the result of (b * b)

byte r = (byte) b * b;

It casts the (byte) type to the first b only, therefore it will become ((byte) b) * b

like image 30
Cyrus Leung Avatar answered Nov 09 '22 04:11

Cyrus Leung


By the precedence rule you are casting only the first b to byte instead of the whole result.

And Java follow some rules, as you can see here

All integer values (byte, short and int) in an arithmetic operations (+, , *, /, %) are converted to int type before the arithmetic operation in performed. However, if one of the values in an arithmetic operation (+, , *, /, %) is long, then all values are converted to long type before the arithmetic operation in performed.

So, by just casting the first b you are doing this:

byte = byte * integer

Hence:

byte = integer

Thus, raised error.

like image 2
israelss Avatar answered Nov 09 '22 02:11

israelss