We all have used syntax’s like
i += j and
i = i + j thousands of times in our day-to-day programming. At first sight, they both look similar. In fact, they will result in the 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 the compiler i += 4.5; System.out.println(i); System.out.println(d1);
The program output:
Weird. Isn’t it? Both are expected to be the same as the operation is same. Why do they have different values? Let’s find out.
Java language specification says the following:
A compound assignment expression of the form
E1 op= E2is 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);
So the value 9 is nothing but a result of loss of precision while converting from double to int.
Always use the compound assignment operator [i += j] very carefully. You should use it only when you are dealing with similar data types. In different data types, results can be incorrect.
Happy Learning !!