Java Reference
In-Depth Information
LISTING 2.5
continued
{
int
keys = 88;
System.out.println ("A piano has " + keys + " keys.");
}
}
OUTPUT
A piano has 88 keys.
In the
PianoKeys
program, two pieces of information are used in the call
to the
println
method. The first is a string, and the second is the variable
keys
. When a variable is referenced, the value currently stored in it is used.
Therefore, when the call to
println
is executed, the value of
keys
, which is
88, is obtained. Because that value is an integer, it is automatically converted
to a string and concatenated with the initial string. The concatenated string is
passed to
println
and printed.
A variable declaration can have multiple variables of the same type declared on
one line. Each variable on the line can be declared with or without an initializing
value. For example:
int
count, minimum = 0, result;
Let's examine a program that changes the value of a variable. Listing 2.6 shows
a program called
Geometry
. This program first declares an integer variable called
sides
and initializes it to
7
. It then prints out the current value of
sides
.
The next line in
main
changes the value stored in the variable
sides
:
sides = 10;
This is called an
assignment statement
because it assigns a value to a variable.
When executed, the expression on the right-hand side of the assignment opera-
tor (=) is evaluated, and the result is stored in the memory location indicated
by the variable on the left-hand side. In this example, the expression is simply
a number,
10
. We discuss expressions that are more involved than this in the
next section.
Search WWH ::
Custom Search