Codectionary / Developer documentation / Java

switch Statement

The switch statement compares a single value against multiple possible cases, offering a cleaner alternative to a long else if chain when checking one variable against many discrete values. Traditional switch statements require a break after each case to prevent 'fall-through' into the next case. Java 14+ introduced a modernized switch expression syntax using arrows (->) that eliminates fall-through and can directly return a value.

Syntax

switch (value) {\n  case option: // code\n    break;\n  default: // code\n}

Examples

Traditional switch Statement

The classic switch syntax, requiring break to prevent fall-through.

int day = 3;
String dayName;

switch (day) {
    case 1:
        dayName = "Monday";
        break;
    case 2:
        dayName = "Tuesday";
        break;
    case 3:
        dayName = "Wednesday";
        break;
    default:
        dayName = "Unknown";
}

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

Grouping Cases

Multiple case labels can share the same code block by stacking them without a break in between.

int month = 4;
String season;

switch (month) {
    case 12:
    case 1:
    case 2:
        season = "Winter";
        break;
    case 3:
    case 4:
    case 5:
        season = "Spring";
        break;
    default:
        season = "Other";
}

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

Modern switch Expression (Java 14+)

Using arrow syntax to return a value directly, with no fall-through and no break needed.

int day = 6;

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

System.out.println(dayType);  // Weekend

Best practices

  • Never forget the break statement in a traditional switch - a missing break causes execution to 'fall through' into the next case
  • Always include a default case to handle unexpected values gracefully
  • Prefer the modern arrow-based switch expression (Java 14+) when your target version supports it - it removes the fall-through pitfall entirely
  • Use switch over a long else if chain when comparing one variable against several specific discrete values

Runtime & versions

Java Virtual Machine. Feature availability depends on the language and runtime version used by your project; consult the official reference below.

Java Language Specification

Specifications & further reading