Open In App

Difference between Simple and Compound Assignment in Java

Many programmers believe that the statement “x += i” is simply a shorthand for “x = x + i”. This isn’t quite true. Both of these statements are assignment expressions. The second statement uses the simple assignment operator (=), whereas the first uses a compound assignment operator. The compound assignment operators are +=, -=, *=, /=, %= etc. The Java language specification says that the compound assignment E1 op= E2 is equivalent to the simple assignment, E1 = (T) ((E1) op (E2)), where T is the type of E1. In other words, compound assignment expressions automatically cast the result of the computation they perform to the type of the variable on their left-hand side. If the type of the result is identical to the type of the variable, the cast has no effect. If, however, the type of the result is wider than that of the variable, the compound assignment operator performs a silent narrowing primitive conversion. Attempting to perform the equivalent simple assignment would generate a compilation error. Consider the following examples- 




// A Java program that uses compound assignment
// for different types.
class GFG{
    public static void main(String s[]) {
    short x = 0;
    int i = 123456;
    x += i;  // Casts result to short
    System.out.println(x);
  }
}

Output:



-7616

You might expect the value of x to be 123456 after this statement executes, but it isn’t; it’s -7616. The int value 123456 is too big to fit in a short. The automatically generated cast. It silently removes the two high-order bytes of the int value. 




// A Java program that uses simple addition
// for different types.
class GFG{
  public static void main(String s[]) {
    short x = 0;
    int i = 123456;
    x = x + i; // Causes compilation error
    System.out.println(x);
  }
}

Output:



prog.java:5: error: incompatible types: possible 
lossy conversion from int to short
x = x + i;
    ^

It is clear from above examples that compound assignment expressions can cause undesirable results and should be used carefully for types like byte, short, or char. If we use them, we must ensure that the type of expression on right is not of higher precision. 


Article Tags :