Changing Variables in JavaΒΆ

Remember that a variable holds a value and that value can change or vary. If you use a variable to keep score you would probably increment it (add one to the current value). You can do this by setting the variable to the current value of the variable plus one (score = score + 1) as shown below.

You can set one variable’s value to a copy of the value of another variable. This won’t change the value of the variable that you are copying from. Step through the code below by clicking the “Forward” button to see how the values of the variables change.

Check your understanding

Mixed up programs

        3-3-2: The following has the correct code to 'swap' the values in x and y (so that x ends up with y's initial value and y ends up with x's initial value), but the code is mixed up and contains one extra block which is not needed in a correct solution.  Drag the needed blocks from the left into the correct order on the right. Check your solution by clicking on the Check Me button.  You will be told if any of the blocks are in the wrong order or if you need to remove one or more blocks.  After three incorrect attempts you will be able to use the Help Me button to make the problem x = 3;
int y = 5;
int temp = 0;
temp = x;
x = y;
y = temp;
y = x; #distractor
Next Section - Naming Variables