Variable names such as number1, number2 and sum actually correspond to locations in the computer's memory. Every variable has a name, a type and a value.
In the addition program in Fig. 6.9, when line 25 executes, the string firstNumber (previously entered by the user in a prompt dialog) is converted to an integer and placed into a memory location to which the name number1 has been assigned by the interpreter. Suppose the user entered the string 45 as the value for firstNumber. The program converts firstNumber to an integer, and the computer places the integer value 45 into location number1, as shown in Fig. 6.10. Whenever a value is placed in a memory location, the value replaces the previous value in that location. The previous value is lost.
Suppose that the user enters 72 as the second integer. When line 26 executes, the pro-gram converts secondNumber to an integer and places that integer value, 72, into location number2; then the memory appears as shown in Fig. 6.11.
Once the program has obtained values for number1 and number2, it adds the values and places the sum into variable sum. The statement
sum = number1 + number2;
performs the addition and also replaces sum’s previous value. After sum is calculated, the memory appears as shown in Fig. 6.12. Note that the values of number1 and number2 ap-pear exactly as they did before they were used in the calculation of sum. These values were used, but not destroyed, when the computer performed the calculation—when a value is read from a memory location, the process is nondestructive.
When variables are declared, they are not assigned values unless specified by the pro-grammer. Assigning the value null to a variable indicates that it does not contain a value.
Copyright © 2018-2020 BrainKart.com; All Rights Reserved. Developed by Therithal info, Chennai.