Same Variable Twice in an Assignment Statement

Classic programmed-learning exercises, refreshed for modern Java and presented in the current MrStyner.com portfolio style.

Modern Java noteThis archive has been refreshed for Java 25 LTS. Core language concepts remain useful, while outdated setup instructions and browser-era Java are labeled or replaced. Java 26 is the current feature release; Java 25 is used here as the stable teaching baseline.
go to previous page   go to home page   hear noise   go to next page

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;

The first statement:

  1. Gets the number on the RIGHT of the equal sign: 5
  2. Puts the 5 in the variable called value.
First Statement Do First First Statement Do Second
Action of the First Statement

The second statement:

  1. Does the calculation on the RIGHT of the equal sign: 12 + value.
    • It looks into the variable value to get the number 5.
    • Then it performs the sum: 12 + 5 resulting in 17
  2. It now looks on the LEFT of the equal sign to see where to put the result. Now puts the 17 in the variable called value.
Second Statement Do First Second Statement Do Second
Action of the Second Statement

Important 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 result. When it is used on the left, it says where in memory to save that result.

The two roles are in separate steps, so they don't interfere with each other. Step 1 performs the calculation using the value the variable starts with. 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 );