Read this chapter, which covers variables and arithmetic operations and order precedence in Java.
15. Same Variable Twice in an Assignment Statement
Answer:
The program will print out:
value now holds: 7
Adding a Number to a Variable
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:
- Gets the number on the RIGHT of the equal sign: 5
- Look on the LEFT of the equal sign to see where to put the result.
- Put the 5 in the variable
value
.
The second statement:
- 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
- Look into the variable
- Look on the LEFT of the equal sign to see where to put the result.
- Put the 17 in the variable
value
.
- Put the 17 in the variable
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 );