If-Else & Switch
Dashboard
Topic 5/30
Home › If-Else & Switch

🔀 If-Else & Switch

Learn how to control the flow of your Java programs using conditional statements like if-else and switch.

If, Else, and If-Else-If Ladder

The if statement executes a block of code only if its condition is true. When dealing with multiple conditions, you can use the if-else-if ladder.

GradeCalculator.java Java
public class GradeCalculator {
    public static void main(String[] args) {
        int score = 85;
        
        if (score >= 90) {
            System.out.println("Grade: A");
        } else if (score >= 80) {
            System.out.println("Grade: B");
        } else if (score >= 70) {
            System.out.println("Grade: C");
        } else {
            System.out.println("Grade: F");
        }
    }
}
Output
Grade: B

Nested If-Else

You can place an if-else statement inside another to test complex conditions. Here is a simulation of a simple ATM logic.

SimpleATM.java Java
public class SimpleATM {
    public static void main(String[] args) {
        boolean hasCard = true;
        int pin = 1234;
        int enteredPin = 1234;
        
        if (hasCard) {
            if (enteredPin == pin) {
                System.out.println("Access Granted.");
            } else {
                System.out.println("Invalid PIN.");
            }
        } else {
            System.out.println("Please insert your card.");
        }
    }
}

Switch Statement (Traditional)

The switch statement is a cleaner alternative to an if-else ladder when checking equality against multiple values. Remember to use break to prevent fall-through.

DayOfWeek.java Java
public class DayOfWeek {
    public static void main(String[] args) {
        int day = 3;
        
        switch (day) {
            case 1:
                System.out.println("Monday");
                break;
            case 2:
                System.out.println("Tuesday");
                break;
            case 3:
                System.out.println("Wednesday");
                break;
            default:
                System.out.println("Other day");
        }
    }
}
Note: Without a break, execution will fall through to the subsequent cases even if they don't match the condition.

Switch Expression (Java 14+)

Modern Java introduced a shorter, less error-prone switch syntax using arrow labels -> that eliminates fall-through and allows returning values.

SeasonFinder.java Java
public class SeasonFinder {
    public static void main(String[] args) {
        String month = "Oct";
        
        String season = switch (month) {
            case "Dec", "Jan", "Feb" -> "Winter";
            case "Mar", "Apr", "May" -> "Spring";
            case "Jun", "Jul", "Aug" -> "Summer";
            case "Sep", "Oct", "Nov" -> "Autumn";
            default -> "Unknown";
        };
        
        System.out.println("Season: " + season);
    }
}