Java Switch Statement

The switch statement is a decision-making structure that allows a variable to be tested against a list of values. Each value is called a case. It is an alternative to a long chain of if-else if statements, especially when checking the same variable against many specific values.

Why Use Switch?

Consider a scenario where a menu option number (1–5) maps to different actions. Writing this with if-else becomes lengthy. The switch statement makes it cleaner, more readable, and easier to maintain.

Basic Syntax

switch (expression) {
    case value1:
        // code for case 1
        break;
    case value2:
        // code for case 2
        break;
    // more cases...
    default:
        // code if no case matches
}
  • expression: A variable or value being evaluated. It can be an int, char, String, or enum.
  • case: Each possible match value.
  • break: Exits the switch block after a matching case runs. Without it, execution falls through to the next case.
  • default: Runs when no case matches. It is optional but recommended.

Example – Day of the Week

public class SwitchDemo {
    public static void main(String[] args) {
        int day = 3;
        String dayName;

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

        System.out.println("Day: " + dayName);
    }
}

Output:

Day: Wednesday

The Importance of break

Without the break keyword, Java continues executing all the cases that follow the matching one — this is called fall-through. In most situations, fall-through is unintended and causes bugs.

Example Without break (Fall-Through)

int x = 1;

switch (x) {
    case 1:
        System.out.println("One");
    case 2:
        System.out.println("Two");
    case 3:
        System.out.println("Three");
}

Output (fall-through occurs):

One
Two
Three

Even though only case 1 matched, all three cases ran because there were no break statements.

Intentional Fall-Through (Rare but Useful)

Sometimes fall-through is used intentionally when multiple cases should produce the same result.

int month = 4;
int days;

switch (month) {
    case 1:
    case 3:
    case 5:
    case 7:
    case 8:
    case 10:
    case 12:
        days = 31;
        break;
    case 4:
    case 6:
    case 9:
    case 11:
        days = 30;
        break;
    case 2:
        days = 28;
        break;
    default:
        days = -1;
}

System.out.println("Days in month " + month + ": " + days);

Output:

Days in month 4: 30

Switch with String

Since Java 7, the switch statement supports String values. This is especially useful for handling user commands or menu-driven programs.

import java.util.Scanner;

public class StringSwitchDemo {
    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        System.out.print("Enter a color (red/green/blue): ");
        String color = sc.nextLine().toLowerCase();

        switch (color) {
            case "red":
                System.out.println("Color is Red – Stop!");
                break;
            case "green":
                System.out.println("Color is Green – Go!");
                break;
            case "blue":
                System.out.println("Color is Blue – Calm down.");
                break;
            default:
                System.out.println("Unknown color.");
        }

        sc.close();
    }
}

Switch with char

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("Satisfactory.");
        break;
    case 'D':
        System.out.println("Needs improvement.");
        break;
    default:
        System.out.println("Invalid grade.");
}

Output:

Good job!

Enhanced Switch Expression (Java 14+)

Java 14 introduced an improved form of the switch statement called a switch expression. It is more concise, eliminates the need for break, and can return values directly.

int day = 5;

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

System.out.println(day + " is a " + type);

Output:

5 is a Weekday

The arrow -> syntax automatically prevents fall-through and makes the code shorter and cleaner.

switch vs if-else

Featureswitchif-else
Best used forSingle variable with many exact valuesRange checks, complex conditions
ReadabilityCleaner for many valuesMore flexible
Supports rangesNoYes
Supports StringsYes (Java 7+)Yes
Fall-throughPossible (needs break)Not applicable

Summary

  • The switch statement evaluates an expression and runs the matching case block.
  • Always use break at the end of each case to prevent fall-through.
  • The default case handles situations where no case matches.
  • switch supports int, char, String, and enum types.
  • The enhanced switch expression (Java 14+) using -> is cleaner and avoids fall-through automatically.

Leave a Comment

Your email address will not be published. Required fields are marked *