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
|
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
|
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
|
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 .