Switch Statement

Naveen AnamaneniUpdated · 5 min read

A lift has a button for each floor. You press 3, and it goes to 3; you don't check "is it floor 1? is it floor 2?" one by one. When a decision depends on one value matching one of several fixed options, Java's switch reads more clearly than a long else-if ladder: it jumps straight to the matching case.

A Switch on a Day Number

DayName.java▶ Try it
public class DayName {
    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 6:
            case 7:
                System.out.println("Weekend");
                break;
            default:
                System.out.println("Another weekday");
        }
    }
}
Output
Wednesday

How it works

  1. Line 4 evaluates day once: it's 3.
  2. Java jumps straight to case 3: and runs its lines.
  3. break on line 13 leaves the switch. Without it, Java would keep going into the next case.
  4. Lines 14 and 15 put two labels on one block, so 6 and 7 both print "Weekend".
  5. default runs when no case matches, like the final else of a ladder.

Try it yourself: set day to 5, then to 7. Which lines print each time?

Fall-Through: What Happens Without break

Without break, execution falls into the next case
FallThrough.java▶ Try it
public class FallThrough {
    public static void main(String[] args) {
        int day = 2;
        switch (day) {
            case 1: System.out.println("Monday");
            case 2: System.out.println("Tuesday");
            case 3: System.out.println("Wednesday");
                break;
            case 4: System.out.println("Thursday");
        }
    }
}
Output
Tuesday
Wednesday

Case 2 has no break, so after printing "Tuesday", execution falls through into case 3 and prints "Wednesday" too, until it reaches a break. Sometimes that's useful (as with 6 and 7 above); usually it's a bug.

What You Can Switch On

AllowedExample
int, short, byte, charswitch (day), switch (grade) with case 'A':
Their wrappersInteger, Character and so on
String (Java 7+)switch (city) with case "Pune":
enumswitch (coachType) with case SLEEPER:
Any object, with patterns (Java 21+)Pattern matching, later in the course

long, float, double and boolean can't be used in a classic switch. Case labels must be constants, and each must be unique: two case 1: labels give duplicate case label.

CitySwitch.java▶ Try it
public class CitySwitch {
    public static void main(String[] args) {
        String city = "Chennai";
        switch (city) {
            case "Mumbai", "Pune" -> System.out.println("Western zone");
            case "Chennai", "Bengaluru" -> System.out.println("Southern zone");
            default -> System.out.println("Other zone");
        }
    }
}
Output
Southern zone

This is the arrow form (->), added in Java 14. Each case runs only its own line, with no fall-through and no break needed, and one case can list several values with commas. The next lesson, "Switch Expressions", builds on it.

Common Mistakes

Forgetting break. The classic switch bug: one case runs into the next. Prefer the arrow form, which has no fall-through.

Using a variable as a case label. case limit: doesn't compile unless limit is a compile-time constant (static final).

Leaving out default. Without it, an unexpected value silently does nothing. Add default to handle or report it.

Under the Hood

A switch on an int usually compiles to a single jump table instruction (tableswitch or lookupswitch), so the JVM goes straight to the right case instead of comparing one by one. A switch on a String is compiled into a switch on the string's hashCode(), followed by an equals() check, which is why a null string fails with a hashCode message.

Interview Corner

What is fall-through in a switch statement?

In the classic colon form, execution starts at the matching case and continues through the following cases until it reaches a break or the end of the switch. Forgetting break makes several cases run. The arrow form (case X ->) doesn't fall through.

Which types can a switch statement use?

byte, short, char, int, their wrapper classes, String (since Java 7) and enums. Since Java 21, pattern matching lets a switch test any reference type. long, float, double and boolean aren't allowed in a classic switch.

Practice

  1. Easy: Write a switch that prints the name of a month (1 to 12), with default printing "Invalid month".
  2. Harder: Using fall-through on purpose, print the number of days in a month (ignore leap years), grouping 4, 6, 9 and 11 under one block.

Quick check: Switch statement

4 questions
1What happens when a case has no break in the classic form?
2Which type can't be used in a classic switch?
3When does default run?
4What does case "Mumbai", "Pune" -> do?

Key Takeaways

Was this tutorial helpful?

Lesson 55 of 482