Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

        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.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading