Control Flow

Java Switch Statement

Learn how to use switch statements in Java for multi-way branching — traditional switch, enhanced switch expressions, and best practices.

What is a Switch Statement?

The switch statement is a multi-way branch that tests a variable against a list of values (cases). It's a cleaner alternative to long if-else-if chains when comparing a single variable.

java
switch (variable) {
    case value1:
        // code
        break;
    case value2:
        // code
        break;
    default:
        // code if no case matches
}

Basic Switch Example

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;
            case 4:
                System.out.println("Thursday");
                break;
            case 5:
                System.out.println("Friday");
                break;
            case 6:
                System.out.println("Saturday");
                break;
            case 7:
                System.out.println("Sunday");
                break;
            default:
                System.out.println("Invalid day");
        }
    }
}

Output:

Wednesday

The break Statement

The break keyword exits the switch block. Without it, execution falls through to the next case:

java
// Without break — fall-through behavior
int num = 1;
switch (num) {
    case 1:
        System.out.println("One");
        // No break — falls through!
    case 2:
        System.out.println("Two");
    case 3:
        System.out.println("Three");
}
// Output: One Two Three (all three print!)

Intentional Fall-Through

Sometimes fall-through is useful for grouping:

java
int month = 3;
String season;

switch (month) {
    case 12: case 1: case 2:
        season = "Winter";
        break;
    case 3: case 4: case 5:
        season = "Spring";
        break;
    case 6: case 7: case 8:
        season = "Summer";
        break;
    case 9: case 10: case 11:
        season = "Autumn";
        break;
    default:
        season = "Invalid";
}

System.out.println(season);  // Spring

Switch with Strings

Java supports String in switch (since Java 7):

java
String command = "start";

switch (command.toLowerCase()) {
    case "start":
        System.out.println("Starting the system...");
        break;
    case "stop":
        System.out.println("Stopping the system...");
        break;
    case "restart":
        System.out.println("Restarting the system...");
        break;
    default:
        System.out.println("Unknown command: " + command);
}

Enhanced Switch Expression (Java 14+)

Modern Java provides a cleaner syntax using arrow labels and switch expressions:

java
int day = 3;

String dayName = switch (day) {
    case 1 -> "Monday";
    case 2 -> "Tuesday";
    case 3 -> "Wednesday";
    case 4 -> "Thursday";
    case 5 -> "Friday";
    case 6 -> "Saturday";
    case 7 -> "Sunday";
    default -> "Invalid";
};

System.out.println(dayName);  // Wednesday

Benefits of enhanced switch:

  • No break needed — no fall-through
  • Can return values — use as an expression
  • Multiple labels per case: case 1, 7 -> "Weekend"
  • Cleaner syntax with arrow (->)

Supported Data Types

TypeSupportedSince
byte, short, intJava 1
charJava 1
StringJava 7
enumJava 5
long, float, double
boolean

Practical Example

java
import java.util.Scanner;

public class SimpleCalculator {
    public static void main(String[] args) {
        Scanner scanner = new Scanner(System.in);

        System.out.print("Enter first number: ");
        double a = scanner.nextDouble();

        System.out.print("Enter operator (+, -, *, /): ");
        char operator = scanner.next().charAt(0);

        System.out.print("Enter second number: ");
        double b = scanner.nextDouble();

        double result = switch (operator) {
            case '+' -> a + b;
            case '-' -> a - b;
            case '*' -> a * b;
            case '/' -> {
                if (b == 0) {
                    System.out.println("Error: Division by zero");
                    yield 0;
                }
                yield a / b;
            }
            default -> {
                System.out.println("Invalid operator");
                yield 0;
            }
        };

        System.out.printf("%.2f %c %.2f = %.2f%n", a, operator, b, result);
        scanner.close();
    }
}

Summary

  • switch tests a variable against multiple case values
  • Always use break in traditional switch to prevent fall-through
  • Java 14+ switch expressions with -> are cleaner and safer
  • Switch supports int, char, String, and enum types
  • Use default to handle unmatched cases
  • Group related cases using multiple labels or intentional fall-through