This book is now obsolete Please use CSAwesome instead.

3.3. 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

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 <b>one extra block</b> 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 <i>Check Me</i> 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 <i>Help Me</i> button to make the problem easier.

You have attempted of activities on this page