Java Reference
In-Depth Information
The “or” Operator
||
You can form a more elaborate Boolean expression by combining two simpler Boolean
expressions using the “or” operator
||
.
SYNTAX (FOR A BOOLEAN EXPRESSION USING
||
)
(
Boolean_Exp_1
)
||
(
Boolean_Exp_2
)
EXAMPLE (WITHIN AN
if-else
STATEMENT)
if
((salary > expenses)
||
(savings > expenses))
System.out.println("Solvent");
else
System.out.println("Bankrupt");
If
salary
is greater than
expenses
or
savings
is greater than
expenses
(or both), then
the first
System.out.println
statement is executed; otherwise, the second
System.
out.println
statement is executed.
PITFALL: Strings of Inequalities
Do not use a string of inequalities such as
min < result < max
. If you do, your
program will produce a compiler error message. Instead, you must use two inequalities
connected with an
&&
, as follows:
■
(min < result) && (result < max)
Self-Test Exercises
17. Write an
if-else
statement that outputs the word “Passed” provided the
value of the variable
exam
is greater than or equal to 60 and also the value
of the variable
programsDone
is greater than or equal to 10. Otherwise, the
if-else
statement should output the word “Failed“. The variables
exam
and
programsDone
are both of type
int
.
18. Write an
if-else
statement that outputs the word “Emergency” provided the value
of the variable
pressure
is greater than 100 or the value of the variable
temperature
is greater than or equal to 212. Otherwise, the
if-else
statement should output
the word “OK“. The variables
pressure
and
temperature
are both of type
int
.
Evaluating Boolean Expressions
Boolean expressions are used to control branch and loop statements. However, a
Boolean expression has an independent identity apart from any branch statement or
loop statement you might use it in. A Boolean expression returns either
true
or
false
.