Multiple Assignments in a statement

For Java 11 Certification Exam Practice Questions, refer http://talks.skilltoz.com/java-11-certification-exam-questions/

In this article, let us discuss how multiple assignment operators work in a single statement, from the Java 11 certification perspective.

Java allows the use of multiple assignments in one statement. Where there are multiple assignment operators, these are applied from right to left, rather than from left to right.

For example, the statement i = j = k = 2;
first assigns the value 2 to k, then the value of k is assigned to j, and finally the value of j is assigned to i. Thus, the given statement is equivalent to i = (j = (k = 2));

All types of assignment operators can be mixed in a multiple assignment statement.

For example, assume that i, j, and k are int variables with values 1, 2, and 3 respectively.
Then the statement i /= j -= k + 4; would be evaluated as follows:

  i /= j = j - (k + 4);
  i /= j = 2 - (3 + 4);
  i /= j = 3;
  i = i / (j);
  i = 1 / (3);
  i = 0;

The final values of i, j, and k would be 0, 3, and 3 respectively.

References

For more information on this topic, you can refer https://docs.oracle.com/javase/tutorial/java/nutsandbolts/op1.html

Leave a Reply

Your email address will not be published. Required fields are marked *