Java Reference
In-Depth Information
A Java statement such as:
num = num + 2;
means ''evaluate whatever is in
num
, add
2
to it, and assign the new value to the memory
location
num
.'' The expression on the right side must be evaluated first; that value is then
assigned to the memory location specified by the variable on the left side. Thus, the
sequence of Java statements:
2
num = 6;
num = num + 2;
and the statement:
num = 8;
both assign
8
to
num
. Note that the statement
num = num + 2
is meaningless if
num
has not
been initialized.
The statement
num = 5;
is read as ''
num
becomes
5
'' or ''
num
gets
5
'' or ''
num
is assigned
the value
5
.'' Each time a new value is assigned to
num
, the old value is erased.
Suppose that num is an
int
variable. Consider the statement:
num = num + 2;
. This
statement adds
2
to the value of
num
, and the new value is assigned to the variable
num
.
If the variable
num
is not properly initialized, then the Java complier will generate a
syntax error. So to use the value of a variable in an expression, the variable must
be properly initialized. Variable initialization is further covered in the next section,
''Declaring and Initializing Variables.''
EXAMPLE 2-14
Suppose that
num1
,
num2
, and
num3
are
int
variables and the following statements are
executed in sequence.
1.
num1 = 18;
2.
num1 = num1 + 27;
3.
num2 = num1;
4.
num3 = num2 / 5;
5.
num3 = num3 / 4;
Table 2-4 shows the values of the variables after the execution of each statement. (A ?
indicates that the value is unknown. The orange color in a box shows that the value of
that variable is changed.)
Search WWH ::
Custom Search