In the previous lesson you learnt about logical operators and the if condition:
Compound operators
If you need to test more than one condition at the same time you can use the logical and operator && or the logical or operator ||:
// Compound operators
int i = 3;
int j = 4;
double x = 8.4;
double y = 9.7;
// Logical and: both must be true
if ((i < j) && (x > y)) {
// the first comparison is true and the second is false
// therefore the final result is false and this block of
// code will not be entered.
System.out.println("Should not be output");
}
// Logical or: either (or both) must be true
if ((i < j) || (x > y)) {
// the first comparison is true and the second is false
// therefore the final result is true and this block of
// code will be entered.
System.out.println("Should be output");
}
Both above operators only make the second comparison if the first one does not preclude the final result. For example, in the first example above, had i not been less than j then the second comparison of x and y would not have taken place, since it would not affect the final outcome. Similarly, in the second example above, because i is less than j there is no need to test x and y.
Your condition expression may include several compound tests, and you can also include the ! symbol to negate the test:
// Using ! with compound comparisons
boolean sunny = true;
boolean raining = false;
boolean cold = false;
boolean windy = true;
if (sunny && !raining && !cold && windy) {
System.out.println("It is sunny, not raining, " +
"not cold and is windy");
}
Java also includes the logical operators & (for and) and | (for or) where they each always test all parts of the comparison, even if it is unnecessary. It is recommended that you use && and || for your comparisons.
If you have methods that return a boolean these can also be used as the conditional expression:
private int temperature = 27;
public boolean isHot() {
return (temperature >= 25);
}
public void weatherCheck() {
if (isHot()) {
System.out.println(“It is hot”);
}
}
To negate a conditional for a method you can prefix the ! symbol:
if (! isHot()) {
System.out.println(“It is not hot”);
}
In the next lesson you will learn about if...else... blocks.
Comments