In the previous lesson you learnt about compound operators.
The if else block
You can use the else statement when you need to specify what should happen if the condition is not met. For example, you could modify the weatherCheck() method from the previous lesson:
public void weatherCheck() {
if (isHot()) {
System.out.println(“It is hot”);
} else {
System.out.println(“It is not hot”);
}
}
You can also use else to test several alternate conditions:
public String whatShouldIWear(int temperature) {
String clothing;
if (temperature < 2) {
clothing = “winter coat”;
} else if (temperature < 10) {
clothing = “wooly jumper”;
} else if (temperature < 15) {
clothing = “suit”;
} else if (temperature < 21) {
clothing = “t-shirt”;
} else if (temperature < 27) {
clothing = “shorts”;
} else {
clothing = “suncream”;
}
return clothing;
}
The following snippet shows an example of using the above method:
String myClothes = whatShouldIWear(23); // myClothes should contain "shorts"
In the next lesson you will learn about the ternary operator.
Comments