Java Reference
In-Depth Information
Common Error 3: Redundant Testing of Boolean Values
To test whether a
boolean
variable is
true
or
false
in a test condition, it is redundant to
use the equality comparison operator like the code in (a):
Equivalent
if
(even ==
true
)
System.out.println(
"It is even."
);
if
(even)
System.out.println(
"It is even."
);
This is better
(a)
(b)
Instead, it is better to test the
boolean
variable directly, as shown in (b). Another good
reason for doing this is to avoid errors that are difficult to detect. Using the
=
operator instead
of the
==
operator to compare the equality of two items in a test condition is a common error.
It could lead to the following erroneous statement:
if
(even
=
true
)
System.out.println(
"It is even."
);
This statement does not have compile errors. It assigns
true
to
even
, so that
even
is
always
true
.
Common Error 4: Dangling
else
Ambiguity
The code in (a) below has two
if
clauses and one
else
clause. Which
if
clause is matched by
the
else
clause? The indentation indicates that the
else
clause matches the first
if
clause.
However, the
else
clause actually matches the second
if
clause. This situation is known as
the
dangling else ambiguity
. The
else
clause always matches the most recent unmatched
if
clause in the same block. So, the statement in (a) is equivalent to the code in (b).
dangling else ambiguity
int
i =
1
, j =
2
, k =
3
;
int
i =
1
, j =
2
, k =
3
;
Equivalent
if
(i > j)
(i > k)
System.out.println(
"A"
);
if
(i > j)
(i > k)
System.out.println(
"A"
);
if
if
This is better
with correct
indentation
else
else
System.out.println(
"B"
);
System.out.println(
"B"
);
(a)
(b)
Since
(i > j)
is false, nothing is displayed from the statements in (a) and (b). To force
the
else
clause to match the first
if
clause, you must add a pair of braces:
int
i =
1
, j =
2
, k =
3
;
if
(i > j)
if
(i > k)
System.out.println(
"A"
);
{
}
else
System.out.println(
"B"
);
This statement displays
B
.