Java Reference
In-Depth Information
System.out.print("Cash is dangerously low. Bet carefully.");
} else if (money < 1000) {
System.out.print("Cash is somewhat low. Bet moderately.");
} else {
System.out.print("Cash is in good shape. Bet liberally.");
}
System.out.print("How much do you want to bet? ");
bet = console.nextInt();
Multiple Conditions
When you are writing a program, you often find yourself wanting to test more than
one condition. For example, suppose you want the program to take a particular
course of action if a number is between 1 and 10. You might say:
if (number >= 1) {
if (number <= 10) {
doSomething();
}
}
In these lines of code, you had to write two statements: one testing whether the
number was greater than or equal to 1 and one testing whether the number was less
than or equal to 10.
Java provides an efficient alternative: You can combine the two tests by using an
operator known as the logical AND operator, which is written as two ampersands
with no space in between ( && ). Using the AND operator, we can write the preceding
code more simply:
if (number >= 1 && number <= 10) {
doSomething();
}
As its name implies, the AND operator forms a test that requires that both parts of
the test evaluate to true . There is a similar operator known as logical OR that evalu-
ates to true if either of two tests evaluates to true . The logical OR operator is writ-
ten using two vertical bar characters ( || ). For example, if you want to test whether a
variable number is equal to 1 or 2, you can say:
if (number == 1 || number == 2) {
processNumber(number);
}
We will explore the logical AND and logical OR operators in more detail in the
next chapter.
 
Search WWH ::




Custom Search