Assignment operators
The Assignment program
The Assignment program illustrates the right associativity of the assignment operator. This program results in the values 8, 7, and 5 being assigned to the i, j, and k variables.
The heart of the program's processing is the evaluation of the statement:
i += j += k = ++i + ++j;
Since += and = are right-associative, this statement is evaluated as follows:
i += (j += (k = (++i + ++j)));
This results in 5 being assigned to k. The value of 5 is then added to j giving it a value of 7. Finally 7 is added to i resulting in a value of 8.
Assignment
public class Assignment {
public static void main(String[] args) {
int i = 1;
int j = 2;
int k = 3;
i += j += k = ++i + ++j;
System.out.println(i);
System.out.println(j);
System.out.println(k);
}
}
Assignment operators
The assignment operators that you need to know for the exam are =, +=, -=, *=, and /=. The simple assignment operator, =, is the most frequently used operator.
It is used to initialize variables with values and to reassign new values to them. The +=, -=, *=, and /= operators are short forms of addition, subtraction, multiplication and division with assignment.
The += operator can be read as "first add and then assign," and -= can be read as "first subtract and then assign."
Similarly, *= can be read as "first multiply and then assign" and /= can be read as "first divide and then assign."
If you apply these operators to two operands, a and b, they can be represented as follows:
a -= b is equal to a = a - b
a += b is equal to a = a + b
a *= b is equal to a = a * b
a /= b is equal to a = a / b