Java Reference
In-Depth Information
Line 20
System.out.print(
"Enter second integer: "
);
// prompt
prompts
the user to enter the second integer. Line 21
number2 = input.nextInt();
// read second number from user
reads the second integer and assigns it to variable
number2
.
Line 23
sum = number1 + number2;
// add numbers then store total in sum
is an assignment statement that calculates the sum of the variables
number1
and
number2
then assigns the result to variable
sum
by using the assignment operator,
=
. The statement
is read as “
sum
gets
the value of
number1
+
number2
.” When the program encounters the
addition operation, it performs the calculation using the values stored in the variables
number1
and
number2
. In the preceding statement, the addition operator is a
binary oper-
ator
—its
two
operands are the variables
number1
and
number2
. Portions of statements that
contain calculations are called
expressions
. In fact, an expression is any portion of a state-
ment that has a
value
associated with it. For example, the value of the expression
number1
+
number2
is the
sum
of the numbers. Similarly, the value of the expression
input.next-
Int()
is the integer typed by the user.
After the calculation has been performed, line 25
System.out.printf(
"Sum is %d%n"
, sum);
// display sum
uses method
System.out.printf
to display the
sum
. The format specifier
%d
is a
placehold-
er
for an
int
value (in this case the value of
sum
)—the letter
d
stands for “decimal integer.”
The remaining characters in the format string are all fixed text. So, method
printf
dis-
plays
"Sum
is
"
, followed by the value of
sum
(in the position of the
%d
format specifier)
and a newline.
Calculations can also be performed
inside
printf
statements. We could have com-
bined the statements at lines 23 and 25 into the statement
System.out.printf(
"Sum is %d%n"
, (number1 + number2));
The parentheses around the expression
number1
+
number2
are optional—they're included
to emphasize that the value of the
entire
expression is output in the position of the
%d
for-
mat specifier. Such parentheses are said to be
redundant
.
For each new Java API class we use, we indicate the package in which it's located. This
information helps you locate descriptions of each package and class in the Java API docu-
mentation. A web-based version of this documentation can be found at