Short operators += and *=



In Java, it is often required to change the value of a variable with something like in

x = x + y;

It basically adds y to x and assigns it back to x. Java provides a shorter form for this statement.

x += y;

As an example here is the code that

  1. /*
  2.   ReferenceDesigner.com Java Tutorial
  3.   compound assignment statement
  4.   */
  5.  
  6. class compound1{
  7. public static void main (String args[]) {
  8. int x = 2;
  9. int y = 5;
  10.  
  11. x +=3; // Is same as x = x +3, x is now 5
  12. System.out.println("value of x after x +=3 "+ x);
  13. x += y; // Is same as x = x + y; x is now 10
  14. System.out.println("value of x after x +=y "+ x);
  15.  
  16. }
  17.  
  18. }


If you compile and run, you get the following output


value of x after x +=3 5
value of x after x +=y 10




The addition is not the only operator on which compound assignment statement can operate. It can operate on *, / and other operators as well.

x *= y ; // Is same as x = x*y

x /= y; // Is the same as x = x/y;

x %= y; // Is the same as x = x % y;

x <<= y; // Is the same as x = x<
x &= y; is the same as x = x & y;

Special Considerations


Java is a highly "typed" language. What we mean by this - is that, Java, generally requires that the types of the variables in the assignment statements should be same. So, if you write a code like one

  1. class typeissue{
  2. public static void main (String args[]) {
  3. int x = 2;
  4. double y = 5;
  5. x = x + y;
  6. System.out.println("Value of x is "+ x);
  7. }
  8.  
  9. }


Then it will throw compile error. More specifically it will show following error if you compile

error: possible loss of precision
        x = x +y;
              ^
  required: int
  found:    double
1 error



However, if you replace the normal assignment statement with compound assignment statement, it compiles and gives result. So the code



  1. class typeissue{
  2. public static void main (String args[]) {
  3. int x = 2;
  4. double y = 5;
  5. x += y;
  6. System.out.println("Value of x is "+ x);
  7. }
  8. }


Compiles and gives the following output

Value of x is 7

Basically,

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.

As another example the code

    short z = 4;
    x += 3.6;
	


is correct and is equivalent to


    short z = 4;
    z = (short)(z +3.6);
	


and evaluates to 7.

For details about the type conversions on the compound assignment statement please see this doc from Oracle .