Java Reference
In-Depth Information
Compound Arithmetic Assignment Operators
Each of the five basic arithmetic operators (+, -, *, /, and %) has a corresponding compound arithmetic assignment
operator. These operators can be explained better with an example. Suppose you have two variables, num1 and num2 .
int num1 = 100;
byte num2 = 15;
If you want to add the value of num1 to num2 , you would write code as
num2 = (byte)(num2 + num1);
You need to cast the result of num2 + num1 to byte because the data type of the expression is int . The same effect
can be rewritten using the compound arithmetic operator (+=), as follows:
num2 += num1; // Adds the value of num1 to num2
A compound arithmetic assignment operator is used in the following form:
operand1 op= operand2
Here, op is one of the arithmetic operators (+, - , * , / , and % ). operand1 and operand2 are of primitive numeric
data types, where operand1 must be a variable. The above expression is equivalent to the following expression:
operand1 = (Type of operand1) (operand1 op operand2)
For example,
int i = 100;
i += 5.5; // Assigns 105 to i
is equivalent to
i = (int)(i + 5.5); // Assigns 105 to i
There are two advantages of using the compound arithmetic assignment operators.
operand1 is evaluated only once. For example, in i += 5.5 , the variable i is evaluated only
once, whereas in i = (int) (i + 5.5), the variable i is evaluated twice.
The
operand1 before assignment. The cast may
result in a narrowing conversion or an identity conversion. In the above example, the cast is
a narrowing conversion. The expression i + 5.5 is of the type double and the result of this
expression is cast to int . So, the result of double 105.5 is converted to int 105 . If you write
an expression like i += 5 , the equivalent expression will be i = (int)(i + 5) . Because the
type of the expression i + 5 is already int, the casting the result to int again is an identity
conversion.
The result is automatically cast to the type of
 
Search WWH ::




Custom Search