Lesson 21 of 50 – Java Switch Statement
42%

Java Switch Statement

The switch statement is used to execute different blocks of code based on the value of an expression. It is useful when you need to compare one value against several possible cases.

1. What Is a Switch Statement?

A switch statement checks an expression and selects the matching case.

public class Main {
    public static void main(String[] args) {
        int day = 2;

        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("Invalid day");
        }
    }
}
Output:
Tuesday

Since day is 2, the code inside case 2 executes.

2. Syntax of Switch Statement

Basic syntax:

switch (expression) {
    case value1:
        // Code for value1
        break;

    case value2:
        // Code for value2
        break;

    default:
        // Code when no case matches
}
  • switch evaluates the expression.
  • case specifies a possible matching value.
  • break exits the switch statement.
  • default handles unmatched values and is optional.
The break statement is commonly used to prevent execution from continuing into the next case.
3. Switch with Integer Values

You can use a switch statement to select an action based on an integer value.

public class Main {
    public static void main(String[] args) {
        int choice = 3;

        switch (choice) {
            case 1:
                System.out.println("Add");
                break;

            case 2:
                System.out.println("Subtract");
                break;

            case 3:
                System.out.println("Multiply");
                break;

            case 4:
                System.out.println("Divide");
                break;

            default:
                System.out.println("Invalid choice");
        }
    }
}
Output:
Multiply

Change choice to 1, 2, or 4 to display the corresponding operation.

4. The Default Case

The default block executes when no case matches the switch expression. It is similar to the final else block in an if-else ladder.

public class Main {
    public static void main(String[] args) {
        int number = 10;

        switch (number) {
            case 1:
                System.out.println("One");
                break;

            case 2:
                System.out.println("Two");
                break;

            default:
                System.out.println("Number not found");
        }
    }
}
Output:
Number not found

The value 10 does not match either case, so the default block executes.

5. Importance of the Break Statement

In a traditional switch statement, break exits the switch. Without it, execution can continue into subsequent case blocks. This behavior is called fall-through.

public class Main {
    public static void main(String[] args) {
        int number = 1;

        switch (number) {
            case 1:
                System.out.println("One");

            case 2:
                System.out.println("Two");

            case 3:
                System.out.println("Three");
                break;

            default:
                System.out.println("Other");
        }
    }
}
Output:
One
Two
Three

Because the first case has no break, execution continues through cases 2 and 3.

Use break when you want to execute only the matching case. Intentional fall-through is also possible when multiple cases should share behavior.
6. Switch with String Values

Java supports String expressions in switch statements. String cases are matched by their contents and are case-sensitive.

public class Main {
    public static void main(String[] args) {
        String language = "Java";

        switch (language) {
            case "Java":
                System.out.println("Java Programming");
                break;

            case "Python":
                System.out.println("Python Programming");
                break;

            case "PHP":
                System.out.println("PHP Programming");
                break;

            default:
                System.out.println("Unknown language");
        }
    }
}
Output:
Java Programming

If you change the value to "java", the "Java" case will not match because the comparison is case-sensitive.

7. Switch with Character Values

A switch statement can also check a char value.

public class Main {
    public static void main(String[] args) {
        char grade = 'A';

        switch (grade) {
            case 'A':
                System.out.println("Excellent");
                break;

            case 'B':
                System.out.println("Very Good");
                break;

            case 'C':
                System.out.println("Good");
                break;

            case 'F':
                System.out.println("Fail");
                break;

            default:
                System.out.println("Invalid grade");
        }
    }
}
Output:
Excellent

Character literals use single quotation marks, such as 'A'.

8. Multiple Cases for the Same Result

Multiple case labels can share the same block of code. This is useful when several values should produce the same result.

public class Main {
    public static void main(String[] args) {
        int day = 7;

        switch (day) {
            case 1:
            case 7:
                System.out.println("Weekend");
                break;

            case 2:
            case 3:
            case 4:
            case 5:
            case 6:
                System.out.println("Weekday");
                break;

            default:
                System.out.println("Invalid day");
        }
    }
}
Output:
Weekend

Both case 1 and case 7 execute the same block because they appear before the same break.

9. Switch Expression (Modern Java)

Modern Java supports switch expressions that return a value. The arrow syntax (->) avoids accidental fall-through.

public class Main {
    public static void main(String[] args) {
        int day = 2;

        String result = switch (day) {
            case 1 -> "Monday";
            case 2 -> "Tuesday";
            case 3 -> "Wednesday";
            default -> "Other day";
        };

        System.out.println(result);
    }
}
Output:
Tuesday

Switch expressions were finalized in Java 14. This syntax is available in Java 14 and later.

10. Switch Expression with Multiple Labels

Modern switch expressions allow multiple case labels to point to the same result using commas.

public class Main {
    public static void main(String[] args) {
        int day = 6;

        String type = switch (day) {
            case 1, 7 -> "Weekend";
            case 2, 3, 4, 5, 6 -> "Weekday";
            default -> "Invalid day";
        };

        System.out.println(type);
    }
}
Output:
Weekday

This syntax can make code shorter and easier to read when multiple values share the same result.

11. Switch Statement vs If-Else
Switch If-Else
Useful for matching one expression against several values. Useful for ranges and complex Boolean conditions.
Uses case labels. Uses Boolean conditions.
Traditional switch may need break. Does not use case fall-through.
Supports compatible types such as int, char, enum, and String. Can test a wider variety of Boolean expressions.

Example using if-else:

int marks = 75;

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

An if-else ladder is more suitable here because the conditions check ranges of marks.

12. Common Switch Statement Mistakes
Mistake 1: Forgetting break
// Traditional switch
switch (choice) {
    case 1:
        System.out.println("One");
        break;
    case 2:
        System.out.println("Two");
        break;
}
Mistake 2: Using duplicate case values
// Invalid: duplicate case value
// case 1: ...
// case 1: ...
Mistake 3: Assuming String cases ignore case
String language = "java";

switch (language) {
    case "Java":
        System.out.println("Java selected");
        break;
    default:
        System.out.println("No exact match");
}
Output:
No exact match
Mistake 4: Forgetting the default case

A default case is optional, but including one is often helpful for handling unexpected values.

13. Practical Example: Simple Calculator

This program uses a switch statement to select an arithmetic operation.

public class Main {
    public static void main(String[] args) {
        double a = 20;
        double b = 5;
        char operator = '/';

        switch (operator) {
            case '+':
                System.out.println("Result: " + (a + b));
                break;

            case '-':
                System.out.println("Result: " + (a - b));
                break;

            case '*':
                System.out.println("Result: " + (a * b));
                break;

            case '/':
                if (b != 0) {
                    System.out.println("Result: " + (a / b));
                } else {
                    System.out.println("Cannot divide by zero.");
                }
                break;

            default:
                System.out.println("Invalid operator");
        }
    }
}
Output:
Result: 4.0
Lesson Summary:
  • switch selects a block based on a value.
  • case defines matching values.
  • break prevents traditional case fall-through.
  • default handles unmatched values.
  • String and character values can be used in switch statements.
  • Modern switch expressions can return values.

🧠 Quick Quiz

Q1. Which keyword exits a traditional switch block?



Q2. Which block handles unmatched case values?



Q3. What is the output?

int day = 1;

switch (day) {
    case 1:
        System.out.println("Monday");
        break;
    default:
        System.out.println("Other");
}