Let’s create a simple program that will swap the values held in two variables called “firstValue” and “secondValue.” As you follow along, it is helpful to think of variables as boxes that can store only one value. These boxes also have photocopiers to make copies of values and shredders to destroy values
// Declare and initialize the variables int firstValue = 5; int secondValue = 17; int temporary = 0; // Swap the values in firstValue and secondValue temporary = firstValue; firstValue = secondValue; secondValue = temporary;
On the first line of the program, we declared a variable with the name
On the second line of the program, we declared another variable, this one with the name
We declared a third variable on the third line of the program called
We’ve declared all our variables! Now we can start swapping the values. In the fourth line of the program we see that
When we do this, the previous value held in “temporary,” in this case 0, is destroyed and can never be accessed again.
Next, we see that firstValue = secondValue. This means that we are going to get a copy of the value in “secondValue” put it in “firstValue.”
Finally, on the last line of the program, we see that secondValue = temporary.
If we compare the first and last steps of the program, we can see that the values of “firstValue” and “secondValue” have been swapped.