go to previous page   go to home page   go to next page hear noise highlighting

Answer:

The program will print out:

value now holds: 7

Same Variable Twice in an Assignment Statement

Look at the statements:

value = 5;
value = 12 + value;

Assume that value has already been declared. The two statements execute one after the other, and each statement performs two steps.

The first statement:

  1. Gets the number on the RIGHT of the equal sign: 5
  2. Look on the LEFT of the equal sign to see where to put the result.
    • Put the 5 in the variable value.

First Statement Do First

First Statement Do Second



The second statement:

  1. Does the calculation on the RIGHT of the equal sign: 12 + value.
    • Look into the variable value to get the number 5.
    • Perform the sum: 12 + 5 to get 17
  2. Look on the LEFT of the equal sign to see where to put the result.
    • Put the 17 in the variable value.

Second Statement Do First

Second Statement Do Second



Note: A variable can be used on both the LEFT and the RIGHT of the = in the same assignment statement. When it is used on the right, it provides a number used to calculate a value. When it is used on the left, it says where in memory to save that value.

The two roles are in separate steps, so they don't interfere with each other. Step 1 uses the original value in the variable. Then step 2 puts the new value (from the calculation) into the variable.


QUESTION 16:

What does the following program fragment write?

value = 5;
System.out.println("value is: " + value );

value = value + 10;
System.out.println("value is: " + value );

go to previous page   go to home page   go to next page