Java Reference
In-Depth Information
Using a named constant to store fixed data, rather than using the data value itself, has one
major advantage. If the fixed data changes, you do not need to edit the entire program
and change the old value to the new value. Instead, you can make the change at just one
place, recompile the program, and execute it using the new value throughout. In
addition, by storing a value and referring to that memory location whenever the value
is needed, you avoid typing the same value again and again and you prevent typos. If you
misspell the name of the location, the computer might warn you through an error
message, but it will not warn you if the value is mistyped.
Certain data must be modifiable during program execution. For example, after each test,
a student's average test score may change; the number of tests also changes. Similarly, after
each pay increase, an employee's salary changes. This type of data must be stored in
memory cells whose contents can be modified during program execution. In Java,
memory cells whose contents can be modified during program execution are called
variables.
Variable:
A memory location whose content may change during program execution.
The syntax for declaring one variable or multiple variables is:
dataType identifier1, identifier2, ..., identifierN;
EXAMPLE 2-12
Consider the following statements:
double
amountDue;
int
counter;
char
ch;
int
num1, num2;
The first statement tells the compiler to allocate enough memory to store a value of type
double
and call it
amountDue
. Statements 2 and 3 have similar conventions. The fourth
statement tells the compiler to allocate two different memory spaces (each large enough
to store a value of the type
int
), name the first memory space
num1
, and name the second
memory space
num2
.
Java programmers typically use lowercase letters to declare variables. If a variable name is
a combination of more than one word, then the first letter of each word, except the first word,
is uppercase. (For example, see the variable
amountDue
in the preceding example.)
From now on, when we say ''variable,'' we mean a variable memory location.
Search WWH ::
Custom Search