Java for Beginners, Lesson 17: switch Statement in Java (Classic and Modern)

Java for Beginners · Module 4: Control Flow


🎯 When Many Choices Depend on One Value

Suppose a number from 1 to 7 should print a day name. An else-if ladder works, but it repeats the same test again and again. A switch statement is a cleaner way to pick one path based on the value of a single variable.

📌 switch compares one value against a list of case labels and runs the matching case. default runs when nothing matches, and break stops the switch from running into the next case.

1️⃣ Classic switch

switch (day)
day = 3
jump to matching case ➜
case 3:
prints Wednesday
➜
break;
leave the switch
If no case matches, Java runs default. Without break, execution keeps going into the next case.

Figure 1: How an old-style switch finds and runs a case.

Allowed selector typesNot allowed
byte short char intlong
Stringfloat double
enum, wrapper classes (Integer, Character)boolean

Figure 4: What a switch can test.

Program 1: Day of the week

public class SwitchBasic {
    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;
            default:
                System.out.println("Other day");
        }
    }
}
🖥️ Output:
Wednesday
  • The value of day is compared with each case label. Case 3 matches.
  • break jumps out of the switch so the following cases do not run.
  • default is like the final else: it runs when no case matches. It is optional and usually written last.
  • Each case label must be a constant (a literal or a final variable), and no two labels may be equal.

2️⃣ Fall-Through

If break is missing, Java keeps running the following cases, even if their labels do not match. Sometimes this is useful, and sometimes it is a bug.

n = 2Runs?Output
case 1:skipped (no match)–
case 2:match, starts heretwo
case 3:falls throughthree
default:falls throughdefault
With no break, everything from the matching case to the end of the switch runs.

Figure 2: Fall-through when break is missing.

public class FallThrough {
    public static void main(String[] args) {
        int n = 2;
        System.out.println("Without break:");
        switch (n) {
            case 1:
                System.out.println("one");
            case 2:
                System.out.println("two");
            case 3:
                System.out.println("three");
            default:
                System.out.println("default");
        }

        char grade = 'B';
        System.out.print("Grade " + grade + " means: ");
        switch (grade) {
            case 'A':
            case 'B':
                System.out.println("Good");
                break;
            case 'C':
                System.out.println("Average");
                break;
            default:
                System.out.println("Unknown");
        }
    }
}
🖥️ Output:
Without break:
two
three
default
Grade B means: Good
  • In the first switch, case 2 matches and nothing stops it, so “two”, “three” and “default” all print.
  • In the second switch, the empty case 'A': deliberately falls into case 'B':, so both grades share one answer. This is the main good use of fall-through.
  • If you compile the first switch with javac -Xlint:all, the compiler warns about it: [fallthrough] possible fall-through into case.

3️⃣ switch on Characters and Strings

A switch can test char and String values too. Here is a small calculator.

public class Calc {
    public static void main(String[] args) {
        double a = 12, b = 4;
        char op = '/';
        switch (op) {
            case '+': System.out.println(a + b); break;
            case '-': System.out.println(a - b); break;
            case '*': System.out.println(a * b); break;
            case '/':
                if (b != 0) System.out.println(a / b);
                else System.out.println("Cannot divide by zero");
                break;
            default: System.out.println("Invalid operator");
        }
    }
}
🖥️ Output:
3.0
  • The selector is the char in op. Only the matching branch runs.
  • The selector itself cannot be a double, but the values being calculated can be.
  • Inside a case you can use any statements, including an if from Lesson 16.

4️⃣ The Modern switch (Java 14 and later)

Classic switchModern switch (Java 14+)
Separatorcase 1:case 1 ->
break needed?Yes, or it falls throughNo, never falls through
Several valuesstacked casescase 1, 2, 3 ->
Gives a value?NoYes: int x = switch (...) { ... };

Figure 3: Classic switch versus the modern arrow form.

The arrow form removes the need for break, never falls through, and can produce a value directly. Java 21 supports it fully.

public class ModernSwitch {
    public static void main(String[] args) {
        int month = 2;
        int days = switch (month) {
            case 1, 3, 5, 7, 8, 10, 12 -> 31;
            case 4, 6, 9, 11 -> 30;
            case 2 -> 28;
            default -> 0;
        };
        System.out.println("Month " + month + " has " + days + " days");

        String cmd = "stop";
        switch (cmd) {
            case "go" -> System.out.println("Moving");
            case "stop" -> System.out.println("Halted");
            default -> System.out.println("Unknown command");
        }

        String size = "M";
        String label = switch (size) {
            case "S" -> "Small";
            case "M" -> {
                String t = "Medium";
                yield t + " (popular)";
            }
            default -> "Other";
        };
        System.out.println(label);
    }
}
🖥️ Output:
Month 2 has 28 days
Halted
Medium (popular)
  • case 1, 3, 5 -> 31 lists several values in one case, replacing stacked labels.
  • The whole switch is an expression here: its result is stored in days. The expression form must cover every possible value, which is why it has a default.
  • When one case needs several statements, wrap them in braces and return the value with yield.
  • Use this form if your Java version is 14 or later. Older versions only know the classic form, so you should recognise both.

5️⃣ Errors Beginners Meet

Duplicate case label

public class Dup {
    public static void main(String[] args) {
        int x = 1;
        switch (x) {
            case 1: System.out.println("a"); break;
            case 1: System.out.println("b"); break;
        }
    }
}
🖥️ Compiler message:
Dup.java:6: error: duplicate case label
case 1: System.out.println(“b”); break;
^
1 error

A selector type that is not allowed

public class BadType {
    public static void main(String[] args) {
        double d = 2.0;
        switch (d) {
            case 2.0: System.out.println("two"); break;
        }
    }
}
🖥️ Compiler message:
BadType.java:4: error: selector type double is not allowed
switch (d) {
^
1 error
  • Decimals cannot be switched on because they are not exact. Use an if chain for decimals.

A case label that is not a constant

public class NotConst {
    public static void main(String[] args) {
        int x = 2, y = 2;
        switch (x) {
            case y: System.out.println("same"); break;
        }
    }
}
🖥️ Compiler message:
NotConst.java:5: error: constant expression required
case y: System.out.println(“same”); break;
^
1 error
  • A case label must be known at compile time. Make the variable final with a fixed value, or use an if.

⚠️ Common Mistakes

MistakeProblemFix
Forgetting breakFalls into the next caseAdd break, or use the arrow form
Switching on a double or booleanNot allowedUse if-else
Duplicate case valuesCompile errorEach label once
Using a range like case 1..5No ranges in JavaList values, or use if
Mixing : and -> in one switchNot allowedPick one style
Comparing case text with different capitals“Stop” does not match “stop”Convert with toLowerCase() first

❓ Frequently Asked Questions

Q1. Is default required?
No for a statement, but it is good practice. A switch expression needs it unless every value is covered.

Q2. Does default have to be last?
No, but putting it last is the convention. If it is not last, it still needs a break (in the classic form).

Q3. When should I use switch instead of if?
When comparing one variable against several fixed values. Use if for ranges or complex conditions.

Q4. Can a switch test a String?
Yes, since Java 7. The match is case-sensitive.

✅ Key Takeaways

  • switch picks a path by comparing one value to constant case labels.
  • Allowed selectors: byte, short, char, int, String, enum (not long, float, double, boolean).
  • Use break to stop fall-through. Stacked cases share code on purpose.
  • default handles values with no matching case.
  • The modern case x -> form needs no break and can return a value.
🎓 Practice questions: (1) Write a program that prints the name of the month for a number from 1 to 12. (2) Use a switch to tell whether a letter is a vowel or a consonant (stacked cases). (3) Predict the output of the fall-through example if n is 1. (4) Why can a switch not use a double selector? (5) Rewrite the day-of-week program using the arrow form.
All 30 lessons in this series (open course page)

Module 1 · Getting Started

Module 2 · Building Blocks

Module 3 · Operators

Module 4 · Control Flow

Module 5 · Data and Methods

Module 6 · Objects and Revision