Java switch Statement

In the last lesson you learned about the Java else-if ladder. But checking one variable against many exact values, like a menu choice of 1, 2, 3, or 4, makes a long ladder repetitive. Java has a cleaner tool for this: the switch statement.

🤔 Why switch over a long ladder?

A coffee machine looks at the one button you press and jumps straight to that drink. A switch thinks the same way. An else-if ladder makes you repeat choice == 1, choice == 2, choice == 3 line after line. A switch names the variable once, then lists the values:

  • Cleaner: the variable appears only once.
  • Clear intent: anyone sees “this is a one-value lookup”.
  • Faster for many cases: Java jumps straight to the match instead of testing each line.

Rule of thumb: ladder for ranges like score >= 80, switch for exact matches like choice == 3.

🧩 The switch syntax

Here is the classic shape. You give switch a variable, then list a case for each value you want to handle.

switch (variable) {
case value1:
// runs if variable equals value1
break;
case value2:
// runs if variable equals value2
break;
default:
// runs if no case matched
}

Each word has a job:

  • switch (variable) is the value Java looks at and compares.
  • Each case value: is one fixed value to match against.
  • break stops and leaves the switch after a match.
  • default is the catch-all, like a final else, when no case matched.

Now a real one. This turns a day number into a day name, with day set to 3.

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;
default:
System.out.println("Another day");
}

What happens here:

  • day is 3, so Java jumps to case 3 and prints “Wednesday”.
  • break stops the switch, skipping everything below.
  • If day were 9, no case matches, so default runs.

Output

Wednesday

☕ A worked menu example

A small ordering menu: the user picks a number, and each number maps to one item. This is the classic job a switch was made for.

int choice = 2;
switch (choice) {
case 1:
System.out.println("You ordered: Tea");
break;
case 2:
System.out.println("You ordered: Coffee");
break;
case 3:
System.out.println("You ordered: Orange Juice");
break;
case 4:
System.out.println("You ordered: Water");
break;
default:
System.out.println("Sorry, that item is not on the menu");
}

What happens here:

  • choice is 2, so Java jumps to case 2, prints the coffee line, then break ends it.
  • Want a fifth item? Add one more case, no repeating choice ==.

Output

You ordered: Coffee

The default does real work: if a user types 9, no case matches, so the menu says the item is not on the list, instead of the program doing nothing.

🔤 What types can switch check?

A switch works only on a fixed set of types:

  • Whole numbers: int, short, byte, and char.
  • A String (since Java 7), so you can match text directly.
  • An enum, a fixed set of named options you define yourself.

Here is a switch on a String, matching a command word, with command set to “start”.

String command = "start";
switch (command) {
case "start":
System.out.println("Starting the game...");
break;
case "pause":
System.out.println("Game paused");
break;
case "quit":
System.out.println("Goodbye!");
break;
default:
System.out.println("Unknown command");
}

Key points:

  • Java matches “start” and prints the start line.
  • String matching is case-sensitive, so “Start” would not match “start”.
  • To ignore case, call command.toLowerCase() first, then switch on the result.

Output

Starting the game...

A switch cannot check ranges or conditions.

  • You cannot write case x > 10:. Each case must be one fixed, constant value.
  • For ranges, use the else-if ladder instead.

⚠️ The break is important

Without break, Java keeps running into the next case, even one that does not match. This is called fall-through, and forgetting break is a classic bug.

int day = 1;
switch (day) {
case 1:
System.out.println("Monday");
// ❌ no break here!
case 2:
System.out.println("Tuesday");
break;
default:
System.out.println("Other");
}

What happens here:

  • Java matches case 1 and prints “Monday”.
  • No break, so it falls into case 2 and prints “Tuesday” too, even though day is not 2.
  • Once it lands on a case, it runs line after line until a break or the bottom. The labels below are ignored, but their code still runs.

Output

Monday
Tuesday

That double output is almost never what you want. The fix: put a break at the end of every case.

Always add break, unless you mean to fall through

Forgetting break makes the switch run into the next case by accident. Put a break at the end of every case. There are rare times you want fall-through on purpose, and we will see one next, but as a habit, always add break.

🎯 Grouping cases on purpose

Fall-through is useful when several values should do the same thing. Stack the cases with no code between them, and they all flow into one shared block. This checks weekday vs weekend.

int day = 6;
switch (day) {
case 1:
case 2:
case 3:
case 4:
case 5:
System.out.println("Weekday");
break;
case 6:
case 7:
System.out.println("Weekend");
break;
default:
System.out.println("Invalid day");
}

What happens here:

  • day is 6, matches case 6, which has no code, so it falls into case 7 and prints “Weekend”.
  • This is intentional fall-through: five values share one weekday action, two share one weekend action, with no repeated print line.

Output

Weekend

So fall-through is bad by accident, good when you stack cases on purpose to share one action.

🧠 switch vs the else-if ladder

Here is a grade-to-message lookup written as a ladder.

char grade = 'B';
if (grade == 'A') {
System.out.println("Excellent");
} else if (grade == 'B') {
System.out.println("Good");
} else if (grade == 'C') {
System.out.println("Pass");
} else {
System.out.println("Try again");
}

It works, but grade == repeats on every branch. Now the same thing as a switch.

char grade = 'B';
switch (grade) {
case 'A':
System.out.println("Excellent");
break;
case 'B':
System.out.println("Good");
break;
case 'C':
System.out.println("Pass");
break;
default:
System.out.println("Try again");
}

Both print “Good”, but the switch reads as a clean lookup table with grade named once. Prefer a switch for one variable against exact values, and the ladder for ranges or several different conditions.

✨ The modern switch (arrow form)

Java 14 and above added a cleaner switch using an arrow ->. It needs no break and cannot fall through by accident. Here is the day example in the new style.

int day = 3;
switch (day) {
case 1 -> System.out.println("Monday");
case 2 -> System.out.println("Tuesday");
case 3 -> System.out.println("Wednesday");
default -> System.out.println("Another day");
}

Why the arrow form is nicer:

  • It runs only the matching case’s code, nothing else.
  • No break to remember, and no fall-through trap.
  • Shorter and safer. Still, the older colon form is everywhere in real code, so know both.

Output

Wednesday

You can still group values in the arrow form. Just list them on one line, separated by commas. Here is the weekday and weekend check, the modern way.

int day = 6;
switch (day) {
case 1, 2, 3, 4, 5 -> System.out.println("Weekday");
case 6, 7 -> System.out.println("Weekend");
default -> System.out.println("Invalid day");
}

Same result, much shorter. The commas do the grouping that stacked case labels did in the old form.

Output

Weekend

🎁 A quick look at switch expressions

A switch can also produce a value instead of just printing. That is a switch expression. You assign the whole switch to a variable, and each arrow gives the value for that case.

int day = 3;
String name = switch (day) {
case 1 -> "Monday";
case 2 -> "Tuesday";
case 3 -> "Wednesday";
default -> "Another day";
};
System.out.println(name);

Read the shape:

  • The switch sits on the right of =, so it returns a result.
  • For day of 3, the matching arrow gives “Wednesday”, which goes into name.
  • Note the semicolon ; after the closing brace, since the whole thing is one assignment statement.

Output

Wednesday

When to use each form

Use the classic colon form when you are reading older code or targeting older Java. Use the arrow form for new code, because it avoids the fall-through bug. Use a switch expression when each case should produce a value you then store or return.

⚠️ Common Mistakes

Watch for these:

Forgetting break in the classic form. The code runs past the match into cases that should not run.

// ❌ Wrong: no break, so it falls through
case 1:
System.out.println("One");
case 2:
System.out.println("Two");
// ✅ Right: break stops after the match
case 1:
System.out.println("One");
break;
case 2:
System.out.println("Two");
break;

Using a switch for ranges. It matches exact values, not conditions, so case score > 80: will not compile.

// ❌ Wrong: switch cannot test a range
switch (score) {
case > 80: ...
}
// ✅ Right: use a ladder for ranges
if (score >= 80) {
System.out.println("Great");
}

Matching the wrong type. The case value must match the switch variable’s type. Switch on an int, and the cases must be numbers, not text in quotes.

int code = 1;
// ❌ Wrong: "1" is text, but code is an int
switch (code) {
case "1": ...
}
// ✅ Right: 1 is a number, matching the int
switch (code) {
case 1:
System.out.println("Found");
break;
}

Forgetting default. Without it, an unmatched value does nothing and gives silent surprises. Add a default so unexpected input is always handled.

✅ Best Practices

Habits that keep your switches clean and safe:

  • Use switch for exact-value checks. One variable against many fixed values is its sweet spot. Leave ranges to the else-if ladder.
  • Always include a default. It catches unexpected values gracefully, instead of letting them slip by unhandled.
  • Add break to every case in the classic form. Or skip the whole problem and use the arrow form, which cannot fall through.
  • Group cases for shared actions. Stack cases (or list them with commas in the arrow form) when several values do the same thing.
  • Keep each case short. If a case needs a lot of code, move that code into a method and call it from the case. The switch stays readable.
  • Prefer the arrow form for new code. It is shorter, and it removes the most common switch bug entirely.

🧩 What You’ve Learned

That wraps up conditions. A quick recap of switch:

  • ✅ The switch statement compares one variable against many fixed values, cleaner than a long ladder.
  • ✅ Each case handles one value, break stops the switch after a match, and default is the catch-all.
  • ✅ switch works on int, char, String, and enum values, but not on ranges.
  • ✅ Without break, the switch falls through into the next case, which is usually a bug, but useful when you group cases on purpose.
  • ✅ The modern arrow form (case 1 ->) needs no break and avoids fall-through, and a switch expression can return a value.

Check Your Knowledge

Test what you learned. Pick an answer for each question, then click Check.

  1. 1

    When is a switch statement a better choice than an else-if ladder?

    Why: switch shines when you compare one variable against several fixed, exact values, like menu choices.

  2. 2

    What does break do in a switch?

    Why: break ends the switch after a case runs, so it does not fall into the next case.

  3. 3

    What happens if you forget break in the classic switch?

    Why: Without break, execution falls through into the following case, even if it does not match. That is usually a bug.

  4. 4

    Which of these can a switch statement check directly?

    Why: switch matches one variable against fixed values of types like int, char, String, and enum. Ranges and conditions belong to an if-else ladder.

🚀 What’s Next?

You can now make any decision in Java. Next comes one of the most powerful ideas in programming: repeating an action many times without copying code. That is what loops are for. Let’s start with the for loop.

Java for Loop

Share & Connect