Java Reference
In-Depth Information
The program can decide which statements to execute based on a condition.
Key
Point
If you enter a negative value for
radius
in Listing 2.2, ComputeAreaWithConsoleInput.java,
the program displays an invalid result. If the radius is negative, you don't want the program to
compute the area. How can you deal with this situation?
Like all high-level programming languages, Java provides
selection statements
: statements
that let you choose actions with two or more alternative courses. You can use the following
selection statement to replace lines 12-17 in Listing 2.2:
problem
selection statements
if
(radius <
0
) {
System.out.println(
"Incorrect input"
);
}
else
{
area = radius * radius *
3.14159
;
System.out.println(
"Area is "
+ area);
}
Selection statements use conditions that are Boolean expressions. A
Boolean expression
is
an expression that evaluates to a
Boolean value
:
true
or
false
. We now introduce Boolean
types and comparison operators.
Boolean expression
Boolean value
Key
Point
How do you compare two values, such as whether a radius is greater than
0
, equal to
0
, or less
than
0
? Java provides six
comparison operators
(also known as
relational operators
), shown
in Table 3.1, which can be used to compare two values (assume radius is
5
in the table).
boolean
data type
comparison operators
T
ABLE
3.1
Comparison Operators
Java Operator
Mathematics Symbol
Name
Example (radius is 5)
Result
less than
<
radius < 0
false
<
-
less than or equal to
<=
radius <= 0
false
greater than
>
>
radius > 0
true
-
greater than or equal to
radius >= 0
>=
true
equal to
==
=
radius == 0
false
/
not equal to
!=
radius != 0
true
Note
You can also compare characters. Comparing characters is the same as comparing their
Unicodes. For example,
a
is larger than
A
because the Unicode of
a
is larger than the
Unicode of
A
. See Appendix B, The ASCII Character Set, to find the order of characters.
compare characters
Caution
The equality comparison operator is two equal signs (
==
), not a single equal sign (
=
).
The latter symbol is for assignment.
== vs. =
The result of the comparison is a Boolean value:
true
or
false
. For example, the follow-
ing statement displays
true
:
double
radius =
1
;
System.out.println(radius >
0
);