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 pro-
gram 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 vari-
able programsDone is greater than or equal to 10. Otherwise, the if-else state-
ment 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 Bool-
ean 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 . A
variable of type boolean can store the values true and false . Thus, you can set a vari-
able of type boolean equal to a Boolean expression. For example:
Search WWH ::




Custom Search