I have written the code:
int x = 18;
x *= 0.90;
System.out.println(x);
This code printed 16
However, when I wrote
int x = 18;
x = x * 0.90;
System.out.println(x);
it gave me the following error: incompatible types: possible lossy conversion from double to int
I expected both of these code examples to result in the exact same error as x *= y; is the same as x = x * y;, but x *= 0.90; somehow works and x = x * 0.90; does not. Why is this the case?
>Solution :
Because the Java Language Specifcation (JLS) says so. It’s a bit odd, but, when using the compound assignment operators (*=, +=, etcetera), the cast is implied.
See JLS §15.26.2 which clearly shows the cast in the example right at the top of that section.
Why does it do that? Well, I don’t think SO is the right place to ask ‘what were the designers thinking 30 years ago when this part of the JLS spec was written up’. If I had to take a completely wild stab in the dark, it’s probably the same reason underlying almost all weird java lang spec decisions: "Because C did it that way".
At which point you might ask why did the C designers do it that way. Probably because B did it that way. At which point you might ask why the B designers did it that way. Fortunately, there’s the same people more or less (Ken Thompson and Dennis Ritchie). They’re still alive and respectively 80 and 70 years old. As far as I am aware, they do not hang out on Stack Overflow though.