Memory Concepts
Variable names such as number1, number2 and sum actually correspond to locations in the computer's memory. Every variable has a name, a type, a size and a value.
In the addition program of Fig. 2.7, when the statement (line 18)
number1 = input.nextInt(); // read first number from user
executes, the number typed by the user is placed into a memory location to which the name number1 has been assigned by the compiler. Suppose that the user enters 45. The computer places that integer value into location number1, as shown in Fig. 2.8. Whenever a value is placed in a memory location, the value replaces the previous value in that location. The previous value is lost.
Figure 2.8. Memory location showing the name and value of variable number1.
When the statement (line 21)
number2 = input.nextInt(); // read second number from user
executes, suppose that the user enters 72. The computer places that integer value into location number2. The memory now appears as shown in Fig. 2.9.
Figure 2.9. Memory locations after storing values for number1 and number2.
After the program of Fig. 2.7 obtains values for number1 and number2, it adds the values and places the sum into variable sum. The statement (line 23)
sum = number1 + number2; // add numbers
performs the addition, then replaces sum's previous value. After sum has been calculated, memory appears as shown in Fig. 2.10. Note that the values of number1 and number2 appear exactly as they did before they were used in the calculation of sum. These values were used, but not destroyed, as the computer performed the calculation. Thus, when a valueis read from a memory location, the process is nondestructive.
Figure 2.10. Memory locations after calculating and storing the sum of number1 and number2.