Compound assignment operator [i += j] is not same as [i = i + j] in java

We all have used syntax’s like i += j and i = i + j thousands of times in our day to day programming. In first sight, they both look similar. In fact, they will result in same output in almost all of the cases in practical cases. But, to surprise you they are not similar. In run-time, they are treated differently when i and j are of different types. Let’s look at the example below:

int i = 5;
      
double d1 = (double)i + 4.5; //necessary to satisfy compiler
i += 4.5;

System.out.println(i);
System.out.println(d1);

Output:

9
9.5

Weird. Isn’t it. Both are expected to be same as operation is same. Why they have different values? Let’s find out.

Reason

Java language specification says following:

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.

So effectively our original example code can be re-written as below:

int i = 5;
   
double d1 = (double) i + 4.5;    
i = (int)(i + 4.5); 		//Result converted to int

System.out.println(i);
System.out.println(d1);

Output:

9
9.5

So the value 9 is nothing but a result of loss of precision while converting from double to int.

Lesson Learned

Always use the compound assignment operator [i += j] very carefully. You should use only when you are dealing with similar data types. In different data types, result can be incorrect.

Happy Learning !!

References

http://stackoverflow.com/questions/8710619/java-operator
http://docs.oracle.com/javase/specs/jls/se5.0/html/expressions.html#15.26.2

3 thoughts on “Compound assignment operator [i += j] is not same as [i = i + j] in java”

  1. Hi Lokesh,
    Haven’t seen this great catch.

    “where T is the type of E1″ is the T anything to do with the Generic Type T and also please tell us if this behaviour found in all the version of Java or only on 1.5 above.

Note:- In comment box, please put your code inside [java] ... [/java] OR [xml] ... [/xml] tags otherwise it may not appear as intended.

Leave a Reply

Your email address will not be published. Required fields are marked *


× six = 30

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>