Java Data and Operators
3. Numeric Data and Operators
3.4. Assignment Operators
In addition to the simple assignment operator (=), Java supplies a number of shortcut assignment operators that allow you to combine an arithmetic operation and an assignment in one operation. These operations can be used with either integer or floating-point operands. For example, the += operator allows you to combine addition and assignment into one expression. The statement
k += 3;
is equivalent to the statement
k = k + 3;
Similarly, the statement
r += 3.5 +2.0 * 9.3 ;
is equivalent to
r = r + (3.5 + 2.0 * 9.3); // i.e., r = r + 22.1;
As these examples illustrate, when using the += operator, the expression on its right-hand side is first evaluated and then added to the current value of the variable on its left-hand side.
Table 5.8 lists the other assignment operators that can be used in combination with the arithmetic operators.
Table 5.8 Java's assignment operators
Operator | Operation | Example | Interpretation |
---|---|---|---|
= | Simple assignment | m=n; |
m=n; |
+= | Addition then assignment | m+=3; |
m=m+3; |
-= | Subtraction then assignment | m-=3; |
m=m-3; |
*= | Multiplication then assignment | m*=3; |
m=m*3; |
/= | Division then assignment | m/=3; |
m=m/3; |
%= | Remainder then assignment | m%=3; |
m=m%3; |
For each of these operations, the interpretation is the same: Evaluate the expression on the right-hand side of the operator and then perform the arithmetic operation (such as addition or multiplication) to the current value of the variable on the left of the operator.