Switch Statement in Java: Syntax, Fall-Through, Arrow Switch and Examples

The switch statement in Java compares one value against a list of constant case labels and jumps straight to the matching case. If nothing matches, the optional default runs. It’s a cleaner alternative to a long if-else if chain when one variable is checked against many fixed values, like a day number, a menu choice, or a status string.

Before you start: read If-Else Statements in Java, since switch replaces one specific kind of if-else ladder, and Break and Continue in Java for how break works.

Key Takeaways

  • A classic switch uses case value: labels; without break, execution falls through into the next case.
  • Allowed selector types: byte, short, char, int (and their wrappers), String (Java 7+), and enum. Not long, float, double, or boolean.
  • Case labels must be compile-time constants, with no duplicates.
  • Since Java 14, the arrow form case X -> never falls through, and a switch expression can return a value (using yield for block bodies).
  • Switching on null throws NullPointerException unless you handle it (Java 21 adds case null).

Syntax of the Switch Statement in Java

PartMeaning
switch (expression)The value is evaluated once
case VALUE:An entry point; VALUE must be a constant of a compatible type
break;Leaves the switch; without it, execution continues into the next case
default:The fallback entry point; at most one per switch; conventionally last

Example 1: Day Number to Day Name

Code (Java 21):

Output:

WednesdaySwitch finished

How Does a Switch Statement Work in Java?

Whiteboard
Loading diagram...

Java jumps directly to the matching label instead of testing conditions one by one. From there it keeps running statements until it hits break or the end of the switch. That’s why a missing break changes the result.

Which Data Types Can Be Used in a Java Switch?

Selector typeAllowed?Since
int, short, byte, charYesJava 1.0
Integer, Short, Byte, CharacterYes (auto-unboxed)Java 5
enumYesJava 5
StringYesJava 7
long, float, double, booleanNo (classic switch)—
Any object, via patternsYes, with pattern matchingJava 21

Can We Use long or boolean in a Switch in Java?

No. The compiler rejects both:

LongSwitch.java:4: error: selector type long is not allowed        switch (id) {
^
1 error

BooleanSwitch.java:4: error: selector type boolean is not allowed        switch (ok) {
^
1 error

For a boolean, use if-else. For a long that fits in an int, cast it first (switch ((int) id)), or use if-else.

Switch on char: A Simple Calculator

Code (Java 21):

Output:

20.0 + 8.0 = 28.020.0 - 8.0 = 12.0
20.0 * 8.0 = 160.0
20.0 / 8.0 = 2.5
Unsupported operator: %

A case body can contain any statements, including an if, as the division case shows.

Switch Case With String in Java

Code (Java 21):

Output:

RED: StopGREEN: Go
green: Unknown signal
BLUE: Unknown signal

String matching uses .equals(), so it is case-sensitive: "green" didn’t match "GREEN". Normalize first with signal.toUpperCase() if case shouldn’t matter.

Null strings crash the switch:

Code (Java 21):

Output:

Exception in thread "main" java.lang.NullPointerException: Cannot invoke "String.hashCode()" because "" is null	at NullSwitch.main(NullSwitch.java:4)

Even default doesn’t help, because Java needs the string’s hash code before choosing a case. Guard with if (signal != null) first, or use case null in Java 21 (shown later).

Switch on an enum

An enum is a fixed set of named constants; you’ll study enums later. They pair naturally with switch, and the case labels use the bare constant name:

Code (Java 21):

Output:

LOW: check again next weekMEDIUM: check again tomorrow
HIGH: alert the team now

A classic switch statement doesn’t force you to cover every constant. If someone later adds CRITICAL, this switch silently ignores it. Adding a default that logs unexpected values (or using the switch expression shown later) protects you.

Fall-Through in Switch: Why break Is Used in Switch Case

Without break, Java keeps running into the next case’s statements, whether or not that case’s label matches. This is called fall-through.

The Fall-Through Bug

Code (Java 21):

Output:

 CHILD ticket: Rs 120

Dry Run of the Bug

StepWhere execution ispriceWhy
1Jump to case "CHILD":0 → 50Label matches
2No break, so continue into case "ADULT":50 → 120Fall-through ignores the label
3break120Leave the switch

The child paid the adult price. Adding break; after price = 50; fixes it:

Code (Java 21):

Output:

 CHILD ticket: Rs 50

Review rule: every non-empty case should end in break, return, throw, or continue (when the switch is inside a loop). If it doesn’t, the fall-through must be deliberate and commented.

Grouping Cases (Intentional Fall-Through)

Stacked labels with no code between them share one body. This is the most common and safest use of fall-through.

Code (Java 21):

Output:

Month 2: 29 daysMonth 4: 30 days
Month 7: 31 days
Month 13: invalid

Deliberate Fall-Through With Code Between Cases

Occasionally running “this case and everything after it” is exactly what you want:

Code (Java 21):

Output:

 Remaining setup:  Step 2: verify email
Step 3: set password

The // fall through comments tell readers (and reviewers) that the missing break is intentional.

Does default Have to Be Last?

No, but its position matters if it has no break, because fall-through applies to default too:

Code (Java 21):

Output:

defaulttwo

No case matched 9, so Java jumped to default, then fell through into case 2. Keep default last to avoid surprises.

Case Label Rules and Compile Errors

Case Labels Must Be Constants

NonConstantCase.java:6: error: constant expression required            case limit:
^
1 error

A final variable initialized with a constant is allowed:

Code (Java 21):

Output:

 at limit

No Duplicate Labels

DuplicateCase.java:8: error: duplicate case label            case 1:
^
1 error

Variable Scope Inside a Switch

All cases share one scope, so the same variable name can’t be declared in two cases:

ScopeClash.java:10: error: variable message is already defined in method main(String[])                String message = "Deleted";
^
1 error

Fix: give each case its own block with braces:

Code (Java 21):

Output:

 Deleted

Enhanced Switch in Java: Arrow Syntax (Java 14+)

Java 14 made a new arrow form standard (it was a preview in Java 12 and 13). With case X ->:

  • there is no fall-through, so you never need break;
  • several values share one case with commas: case 6, 7 ->;
  • the right side is a single expression, a { block }, or a throw.

Code (Java 21):

Output:

1: weekday6: weekend
7: weekend
9: invalid day

You can’t mix the two styles in one switch:

MixedKinds.java:6: error: different case kinds used in the switch            case 2:
^
1 error

Switch Expression in Java (Returning a Value)

A switch expression produces a value you can assign directly. Note the semicolon after the closing brace, since the whole switch is part of an assignment.

Code (Java 21):

Output:

CHILD -> Rs 50ADULT -> Rs 120
SENIOR -> Rs 70
VIP -> unknown ticket

This is the ticket pricing from the fall-through bug, rewritten so the bug can’t happen.

What Is yield in a Java Switch?

When a case needs several statements, write a block and hand back the value with yield:

Code (Java 21):

Output:

95: Excellent70: Good
30: Needs improvement (30)

yield also works in a colon-style switch expression:

Code (Java 21):

Output:

Grade B = 3 points 

yield leaves the switch with a value; return would leave the whole method.

Switch Expressions Must Be Exhaustive

A switch expression must produce a value for every possible input:

NotExhaustive.java:4: error: the switch expression does not cover all possible input values        String type = switch (day) {
^
1 error

Add a default. For an enum, covering every constant is enough, and the compiler will flag the switch if a new constant is added later:

Code (Java 21):

Output:

LOW: recheck in 60 minMEDIUM: recheck in 15 min
HIGH: recheck in 1 min

Preview: Pattern Matching for Switch (Java 21)

Java 21 lets a switch test the type of a value, add conditions with when, and handle null directly. You’ll understand this fully after the OOP lessons; here is a taste:

Code (Java 21):

Output:

positive int 42non-positive int -7
text of length 5
no value
something else: 3.5

case null removes the NullPointerException problem, and when adds a condition to a case. This needs Java 21 or later.

Switch vs If-Else in Java

SituationBetter choice
One variable compared against many fixed constantsswitch
Ranges (marks >= 90)if-else
Conditions on different variables (age > 18 && hasId)if-else
boolean, long, double valuesif-else
Computing a value from fixed optionsswitch expression
Branching on the type of an object (Java 21+)pattern-matching switch

Common Mistakes With Switch in Java

  1. Forgetting break in classic switch, which causes silent fall-through. Use arrow syntax to rule this out.
  2. Switching on a possibly-null String or enum, which throws NullPointerException. Guard it, or use case null (Java 21).
  3. Expecting case-insensitive String matching. Normalize with toUpperCase() first.
  4. Using long, double, float, or boolean as the selector: “selector type … is not allowed”.
  5. Variables or expressions as case labels: “constant expression required”. Use literals, final constants, or enum constants.
  6. Declaring the same variable in two cases without braces: “already defined”.
  7. Mixing : and -> in one switch: “different case kinds used in the switch”.
  8. Leaving out default in a switch expression: “does not cover all possible input values”.

Best Practices

  1. Prefer the arrow form (Java 14+) for new code: no fall-through, shorter, and it can return a value.
  2. Use a switch expression when every branch just computes a value.
  3. Always include a default (or cover every enum constant in an expression) to catch unexpected values.
  4. In classic switches, end every case with break and comment any deliberate fall-through.
  5. Group cases with commas (case 6, 7 ->) or stacked labels instead of copying code.
  6. Keep case bodies short; call a method when a case grows large.
  7. Handle null before the switch (or with case null in Java 21+).

Real-World Example: Café Billing

This program uses a switch expression to look up prices (with a grouped case) and an arrow switch statement to pick a discount band.

Code (Java 21):

Output:

TEA: Rs 20SAMOSA: Rs 25
COFFEE: Rs 40
PIZZA: not on the menu, skipped
TEA: Rs 20
Rs 5 off. Total payable: Rs 100

Lower-case “coffee” still matched because the item was upper-cased first. total / 50 turns the range “100 to 149” into the single constant 2. That’s a common trick for using switch with ranges.

Other everyday uses: menu-driven programs, command parsers, HTTP status handling, game states, unit converters, and mapping codes to messages.

Practice Problems

  1. Easy: Print the number of days in a month (1–12), grouping the 30- and 31-day months.
  2. Easy: Given a char, print whether it is a vowel or a consonant, using grouped cases.
  3. Easy–Medium: Build a calculator that takes two numbers and an operator (+ - * / %), rejecting division by zero.
  4. Medium: Rewrite Problem 3 as a switch expression that returns the result.
  5. Medium: Convert marks (0–100) into grades using switch (marks / 10) and arrow labels, validating out-of-range input first.

Try them in the ExamAdda online compiler.

Interview Questions on Switch in Java

1. What is fall-through in a switch?
Without break, execution continues into the next case’s statements regardless of its label. The arrow form never falls through.

2. Which types can a switch use?
byte, short, char, int, their wrappers, String (Java 7+), and enum. Not long, float, double, or boolean. Java 21 pattern matching allows any object type.

3. What happens if the switch value is null?
A classic switch throws NullPointerException, even with a default. Java 21 allows case null to handle it.

4. What’s the difference between a switch statement and a switch expression?
A statement performs actions; an expression produces a value (int x = switch (…) { … };) and must cover every possible input.

5. What is yield?
It returns a value from a block inside a switch expression, like return, but only for the switch.

6. Is String matching in switch case-sensitive?
Yes. It uses equals(), so "red" doesn’t match "RED".

7. Can case labels be variables?
Only compile-time constants: literals, final variables initialized with constants, or enum constants. Otherwise you get “constant expression required”.

8. Output of int x = 2; switch (x) { case 1: System.out.print("A"); case 2: System.out.print("B"); case 3: System.out.print("C"); }?
BC. It matches case 2 and falls through into case 3.

Article Summary

  • A switch compares one value against constant case labels and jumps directly to the match; default handles everything else.
  • Classic case X: labels fall through without break, which is useful for grouping but the source of the most common switch bug.
  • Selectors can be byte, short, char, int, wrappers, String, or enum; case labels must be unique constants; null selectors throw unless Java 21’s case null is used.
  • Java 14’s arrow labels remove fall-through, and switch expressions return values with yield and must be exhaustive.
  • Use switch for many fixed values and if-else for ranges, mixed conditions, and booleans.

Conclusion

The switch statement makes multi-way decisions on a single value easier to read than a long if-else ladder. In modern Java, prefer the arrow form and switch expressions: they remove fall-through bugs and let the compiler check that every case is covered. With this lesson, you’ve completed Java’s control-flow statements. Next, learn how to organize code into reusable blocks in Introduction to Methods in Java, and practise with ExamAdda practice questions.

Previous lesson: If-Else Statements in Java
Next lesson: Introduction to Methods in Java

References