Java programming course: 5.7 The if else block

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.

Next lesson: 5.8 The ternary operator


Print
×
Stay Informed

When you subscribe, we will send you an e-mail whenever there are new updates on the site.

Related Posts

 

Comments

No comments made yet. Be the first to submit a comment
Saturday, 13 December 2025

Captcha Image