Java Switch Case

The Java Switch Case statement is used to execute one block of code among many based on the value of an expression. It provides a cleaner alternative to long if-else-if ladders when comparing a single variable to multiple constant values. This tutorial explains the syntax of the switch statement and provides several beginner-friendly examples to illustrate its usage.

In these examples, you’ll see how the switch statement works with different data types, and you’ll also learn about some common pitfalls like fall-through behavior when the break statement is omitted.

1. Syntax

A switch statement contains an expression, one or more case blocks, and an optional default block. Here is the basic syntax:

</>
Copy
switch (expression) {
    case value1:
        // statements
        break;
    case value2:
        // statements
        break;
    // ... other cases ...
    default:
        // statements
}

You can also use braces around the statements in each case block to group multiple statements together:

</>
Copy
switch (expression) {
    case value1: {
        // statements
        break;
    }
    case value2: {
        // statements
        break;
    }
    default: {
        // statements
    }
}

The switch statement evaluates the expression and compares its result with each case label. When a matching case is found, the corresponding block of statements is executed until a break is encountered, which terminates the switch. If no match is found, the default block (if provided) is executed.

2. Examples

1. Switching on an Integer

This example demonstrates a switch statement based on an integer value. The program prints a message based on the value of the variable x.

Main.java

</>
Copy
public class Main {
    public static void main(String[] args) {
        int x = 2;
        switch (x) {
            case 0: {
                System.out.println("x is zero.");
                break;
            }
            case 1: {
                System.out.println("x is one.");
                break;
            }
            case 2: {
                System.out.println("x is two.");
                break;
            }
            default: {
                System.out.println("x has an unexpected value.");
            }
        }
    }
}

Output:

x is two.

In this program, the integer variable x is assigned the value 2. The switch statement evaluates x and finds a matching case with case 2:. The corresponding block prints “x is two.” and the break statement terminates the switch, preventing any further cases from executing.

2. Switching on a String

This example shows how to use a switch statement with a String value. Notice how toLowerCase() is used to ensure the comparison is case-insensitive.

Main.java

</>
Copy
public class Main {
    public static void main(String[] args) {
        someFunction("Teacher");
        someFunction("student");
        someFunction("Principal");
        someFunction("Guest");
    }

    public static void someFunction(String role) {
        switch (role.toLowerCase()) {
            case "student": {
                System.out.println("I'm a student.");
                break;
            }
            case "teacher": {
                System.out.println("I'm a teacher.");
                break;
            }
            case "principal": {
                System.out.println("I'm the principal.");
                System.out.println("I lead the school.");
                break;
            }
            default: {
                System.out.println("Role not recognized.");
            }
        }
        System.out.println();
    }
}

Output:

I'm a teacher.

I'm a student.

I'm the principal.
I lead the school.

Role not recognized.

This program uses a switch statement on the String variable role. The method someFunction converts the input to lowercase to handle different capitalizations, then checks for matching case labels. Depending on the role, it prints the appropriate message. If the input doesn’t match any case, the default block executes and prints “Role not recognized.”

3. Demonstrating Fall-through Behavior

If the break statement is omitted, the switch statement will continue executing subsequent case blocks, a behavior known as fall-through. This example demonstrates fall-through by deliberately leaving out the break in one of the cases.

Main.java

</>
Copy
public class Main {
    public static void main(String[] args) {
        int day = 3;
        System.out.println("Using fall-through:");
        switch (day) {
            case 1:
                System.out.println("Monday");
            case 2:
                System.out.println("Tuesday");
            case 3:
                System.out.println("Wednesday");
            case 4:
                System.out.println("Thursday");
            case 5:
                System.out.println("Friday");
                break;
            default:
                System.out.println("Weekend");
        }
    }
}

Output:

Using fall-through:
Wednesday
Thursday
Friday

In this example, the variable day is set to 3. The switch statement matches case 3: and prints “Wednesday”. Since there is no break after this case, execution falls through and continues with the subsequent cases, printing “Thursday” and “Friday” as well. This demonstrates how fall-through can lead to multiple case blocks executing if not properly terminated with break.

4. Switching on a Character

The switch statement can also be used with char values. In this example, we determine a comment based on a grade represented by a character.

Main.java

</>
Copy
public class Main {
    public static void main(String[] args) {
        char grade = 'B';
        switch (grade) {
            case 'A': {
                System.out.println("Excellent!");
                break;
            }
            case 'B': {
                System.out.println("Good job!");
                break;
            }
            case 'C': {
                System.out.println("Well done!");
                break;
            }
            case 'D': {
                System.out.println("You passed.");
                break;
            }
            case 'F': {
                System.out.println("Better try again.");
                break;
            }
            default: {
                System.out.println("Invalid grade.");
            }
        }
    }
}

Output:

Good job!

This program uses the switch statement to evaluate a char variable grade. Based on the value of grade, the program prints an appropriate message. In this case, since the grade is ‘B’, it prints “Good job!”


Conclusion

In this Java Tutorial, we learned about the Java Switch Case statement and its syntax. We explored several examples that demonstrate how to use switch statements with different data types (such as integers, strings, and characters) and scenarios, including the fall-through behavior when the break statement is omitted.