Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why does the augmented assignement operator in Java give a different result?

Tags:

java

operators

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?

like image 250
Kamalakar Thakare Avatar asked Dec 06 '22 14:12

Kamalakar Thakare


2 Answers

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.

like image 194
AxelH Avatar answered Feb 16 '23 00:02

AxelH


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

enter image description here

like image 44
Max Avatar answered Feb 16 '23 00:02

Max