javaintegerdoublemultiplicationassignment-operator

x = x*0.90; gives lossy conversion error. x*=0.90; does not. Why?


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'.

    EDIT: This answer used to mention 'probably because of C' but as comments show, no, in C neither form requires an explicit cast.