Consider the following piece of code:
class Converter {
public static void main(String args[]) {
byte num = 1;
num = num * 2.5;
System.out.println("Result is: " + num);
}
}
The compiler throws the following error:
error: incompatible types: possible lossy conversion from double to the byte at line 1
If I change the second line of the main()
method and I use the *=
shorthand operator:
class Converter {
public static void main(String args[]) {
byte num = 1;
num *= 2.5;
System.out.println("Result is: " + num);
}
}
The code compiles and runs successfully with the output:
Result is: 2
Why the *=
shorthand operator is behaving differently from the full expression num = num * 2.5
?
From the JLS compound assigment operator documentation, you can see the following example :
For example, the following code is correct:
short x = 3;
x += 4.6;
and results in x having the value 7 because it is equivalent to:
short x = 3;
x = (short)(x + 4.6);
It simply auto cast the result by default.
PS : In this other answer I tried to explain the reason you need to cast an operation like the following using the JLS
short x = 3;
x = x + 1; //Won't compile
It is realativly new so I am open to suggestion there.
According to java language specification "15.26.2. Compound Assignment Operators".
A compound assignment expression of the form E1 op= E2 is equivalent to E1 = (T)((E1) op (E2)), where T is the type of E1, except that E1 is evaluated only once.
And you can saw bytecode of your example after compilation(check instruction 3-10).
3: i2d //convert an int into a double
4: ldc2_w #2 // double 2.5d
7: dmul //multiply two doubles
8: d2i // convert a double to an int
9: i2b //convert an int into a byte
10: istore_1 //store int value into variable 1
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