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
?
(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 byte
s promotes them to int
first, since there is no *
operator for byte
s. 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:
If any operand is of a reference type, it is subjected to unboxing conversion (§5.1.8).
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.
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
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 toint
type before the arithmetic operation in performed. However, if one of the values in an arithmetic operation (+
,−
,*
,/
,%
) islong
, then all values are converted tolong
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With