Java Reference
In-Depth Information
prompt the user to enter the first integer and input the value, respectively. The value is
stored in variable
number1
.
Lines 20-21
System.out.print(
"Enter second integer: "
);
// prompt
number2 = input.nextInt();
// read second number from user
prompt the user to enter the second integer and input the value, respectively. The value is
stored in variable
number2
.
Lines 23-24
if
(number1 == number2)
System.out.printf(
"%d == %d%n"
, number1, number2);
compare
the values of
number1
and
number2
to determine whether they're equal. An
if
statement always begins with keyword
if
, followed by a condition in parentheses. An
if
statement expects one statement in its body, but may contain multiple statements if
they're enclosed in a set of braces (
{}
). The indentation of the body statement shown here
is not required, but it improves the program's readability by emphasizing that the state-
ment in line 24
is part of
the
if
statement that begins at line 23. Line 24 executes only if
the numbers stored in variables
number1
and
number2
are equal (i.e., the condition is
true
).
The
if
statements in lines 26-27, 29-30, 32-33, 35-36 and 38-39 compare
number1
and
number2
using the operators
!=
,
<
,
>
,
<=
and
>=
, respectively. If the condition in one or
more of the
if
statements is
true
, the corresponding body statement executes.
Common Programming Error 2.9
Confusing the equality operator,
==
, with the assignment operator,
=
, can cause a logic er-
ror or a compilation error. The equality operator should be read as “is equal to” and the
assignment operator as “gets” or “gets the value of.” To avoid confusion, some people read
the equality operator as “double equals” or “equals equals.”
Good Programming Practice 2.11
Place only one statement per line in a program for readability.
There's no semicolon (
;
) at the end of the first line of each
if
statement. Such a semi-
colon would result in a logic error at execution time. For example,
if
(number1 == number2);
// logic error
System.out.printf(
"%d == %d%n"
, number1, number2);
would actually be interpreted by Java as
if
(number1 == number2)
;
// empty statement
System.out.printf(
"%d == %d%n"
, number1, number2);
where the semicolon on the line by itself—called the
empty statement
—is the statement
to execute if the condition in the
if
statement is
true
. When the empty statement executes,
no task is performed. The program then continues with the output statement, which
al-
ways
executes,
regardless
of whether the condition is true or false, because the output state-
ment is
not
part of the
if
statement.