Java Reference
In-Depth Information
3.1 Introduction
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 alternative courses. You can use the following selection state-
ment 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 relational operators.
Boolean expression
Boolean value
3.2 boolean Data Type
The boolean data type declares a variable with the value either true or false .
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 relational operators (also known as comparison operators ), shown
in Table 3.1, which can be used to compare two values (assume radius is 5 in the table).
boolean data type
relational operators
T ABLE 3.1
Relational 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
Caution
The equality testing 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 );
A variable that holds a Boolean value is known as a Boolean variable . The boolean
data type is used to declare Boolean variables. A boolean variable can hold one of the
Boolean variable
 
 
 
 
Search WWH ::




Custom Search