Java Reference
In-Depth Information
if
(radius >=
0
)
area = radius * radius * PI;
System.out.println(
"The area "
+
" is "
+ area);
if
(radius >=
0
){
area = radius * radius * PI;
System.out.println(
"The area "
+
" is "
+ area);
}
(a) Wrong
(b) Correct
Common Error 2: Wrong Semicolon at the
if
Line
Adding a semicolon at the end of an
if
line, as shown in (a) below, is a common mistake.
Logic error
Empty block
if
(radius >=
0
);
{
area = radius * radius * PI;
System.out.println(
"The area "
+
" is "
+ area);
}
if
(radius >=
0
) { };
{
area = radius * radius * PI;
System.out.println(
"The area "
+
" is "
+ area);
}
Equivalent
(a)
(b)
This mistake is hard to find, because it is neither a compile error nor a runtime error; it is a
logic error. The code in (a) is equivalent to that in (b) with an empty block.
This error often occurs when you use the next-line block style. Using the end-of-line block
style can help prevent this error.
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 testing operator like the code in (a):
if
(even ==
true
)
System.out.println(
"It is even."
);
if
(even)
System.out.println(
"It is even."
);
Equivalent
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.
Search WWH ::
Custom Search