INSTACK 360

Java Control Flow: If-Else & Switch

Control the execution path of your Java programs using conditional statements.

Beginner 5 min read

Decision Making in Java

Decision making structures have one or more conditions to be evaluated by the program. Java provides several statements for this purpose.

The If-Else Statement

An if statement can be followed by an optional else statement, which executes when the boolean expression is false.

int score = 85;

if (score >= 90) {
    System.out.println("Grade A");
} else if (score >= 80) {
    System.out.println("Grade B");
} else {
    System.out.println("Grade C");
}

The Switch Statement

A switch statement allows a variable to be tested for equality against a list of values. Each value is called a case.

char grade = 'B';

switch(grade) {
    case 'A':
        System.out.println("Excellent!");
        break;
    case 'B':
    case 'C':
        System.out.println("Well done");
        break;
    default:
        System.out.println("Invalid grade");
}

Important: The break statement is crucial. Without it, execution falls through to subsequent cases (known as fall-through).