Java Tutorial
🔍

switch Statement

When you have one variable and need to check it against many specific values, a long chain of else if becomes hard to read — and hard to maintain.

The switch statement is built for exactly this situation. It takes one value, matches it against a list of cases, and runs the matching block.

👉 What you'll learn here:

  • The traditional switch statement — cases, break, and default
  • Fall-through — what happens without break
  • switch with Strings and enums
  • The modern switch expression (Java 14+) — cleaner syntax
  • When to use switch vs if/else

🧘 switch replaces long else if chains — not all if/else.

switch works when you're checking one variable against a list of exact values. It doesn't work for range checks (x > 10), complex conditions (a && b), or String comparisons with .equals(). For those, if/else is still the right tool.

The Problem switch Solves

Consider a program that prints the day name for a number:

Java
1// With else-if — repetitive and verbose: 2if (day == 1) { 3 System.out.println("Monday"); 4} else if (day == 2) { 5 System.out.println("Tuesday"); 6} else if (day == 3) { 7 System.out.println("Wednesday"); 8} else if (day == 4) { 9 System.out.println("Thursday"); 10} else if (day == 5) { 11 System.out.println("Friday"); 12} else if (day == 6) { 13 System.out.println("Saturday"); 14} else if (day == 7) { 15 System.out.println("Sunday"); 16} else { 17 System.out.println("Invalid day"); 18}

With switch:

Java
1// With switch — clean and scannable: 2switch (day) { 3 case 1: System.out.println("Monday"); break; 4 case 2: System.out.println("Tuesday"); break; 5 case 3: System.out.println("Wednesday"); break; 6 case 4: System.out.println("Thursday"); break; 7 case 5: System.out.println("Friday"); break; 8 case 6: System.out.println("Saturday"); break; 9 case 7: System.out.println("Sunday"); break; 10 default: System.out.println("Invalid day"); 11}

Same logic. Half the lines. Instantly scannable — you can see every possible value at a glance.

The Traditional switch Statement

Syntax:

Java
1switch (expression) { 2 case value1: 3 // code for value1 4 break; 5 case value2: 6 // code for value2 7 break; 8 // ... more cases 9 default: 10 // code if no case matches 11}

Breaking down each part:

  • switch (expression) — the value being tested. Must be int, char, String, byte, short, or an enum. Cannot be double, float, long, or boolean.
  • case value: — a specific value to match against. Must be a constant — not a variable.
  • break — exits the switch block. Without it, execution falls into the next case (see fall-through below).
  • default — runs when no case matches. Optional, but recommended. Like else in an if chain.

Complete example:

Java
1import java.util.Scanner; 2 3public class DayPrinter { 4 public static void main(String[] args) { 5 6 Scanner scanner = new Scanner(System.in); 7 System.out.print("Enter day number (1-7): "); 8 int day = scanner.nextInt(); 9 10 switch (day) { 11 case 1: 12 System.out.println("Monday"); 13 break; 14 case 2: 15 System.out.println("Tuesday"); 16 break; 17 case 3: 18 System.out.println("Wednesday"); 19 break; 20 case 4: 21 System.out.println("Thursday"); 22 break; 23 case 5: 24 System.out.println("Friday"); 25 break; 26 case 6: 27 System.out.println("Saturday"); 28 break; 29 case 7: 30 System.out.println("Sunday"); 31 break; 32 default: 33 System.out.println("Invalid day number."); 34 } 35 36 scanner.close(); 37 } 38}

Sample output:

Enter day number (1-7): 3 Wednesday

How switch Works — Step by Step

HOW switch WORKS — switch(day) with day = 3 switch(day) day = 3 case 1 ✗ no match case 2 ✗ no match case 3 ✓ match! case 4 skipped case 5–7 skipped default skipped Wednesday break → exit switch
  1. Java evaluates the switch expression (day = 3)
  2. It compares against each case from top to bottom
  3. When it finds a match (case 3), it runs that block
  4. break exits the entire switch — remaining cases are skipped
  5. If no case matches, default runs

Fall-Through — What Happens Without break

Forgetting break is the most common switch mistake — but fall-through is also sometimes used intentionally.

Without break — fall-through happens:

Java
1int day = 3; 2 3switch (day) { 4 case 1: 5 System.out.println("Monday"); 6 case 2: 7 System.out.println("Tuesday"); 8 case 3: 9 System.out.println("Wednesday"); // ← matches here 10 case 4: 11 System.out.println("Thursday"); // ← falls through! 12 case 5: 13 System.out.println("Friday"); // ← falls through! 14 default: 15 System.out.println("Weekend"); // ← falls through! 16}

Output:

Wednesday Thursday Friday Weekend

Once a case matches, Java executes all subsequent cases regardless of their values — until it hits a break or the end of the switch.

Intentional fall-through — grouping cases:

Fall-through is useful when multiple values should run the same code:

Java
1int month = 4; // April 2 3switch (month) { 4 case 1: 5 case 3: 6 case 5: 7 case 7: 8 case 8: 9 case 10: 10 case 12: 11 System.out.println("31 days"); 12 break; 13 case 4: 14 case 6: 15 case 9: 16 case 11: 17 System.out.println("30 days"); // ← April hits this 18 break; 19 case 2: 20 System.out.println("28 or 29 days"); 21 break; 22 default: 23 System.out.println("Invalid month"); 24}

Output:

30 days

Empty cases stack up — case 4:, case 6:, case 9:, case 11: all fall through to the same println. This is deliberate and clean — no code is repeated.

⚠️ Accidental fall-through is a common bug. Always add break at the end of every case unless you intentionally want fall-through. When fall-through is intentional, add a comment:

Java
1case 4: 2case 6: // fall-through intentional — same days count 3case 9:

switch with Strings

From Java 7 onwards, switch works with String values:

Java
1String season = "Winter"; 2 3switch (season) { 4 case "Spring": 5 System.out.println("Flowers bloom."); 6 break; 7 case "Summer": 8 System.out.println("Hot and sunny."); 9 break; 10 case "Autumn": 11 System.out.println("Leaves fall."); 12 break; 13 case "Winter": 14 System.out.println("Cold and dry."); // ← matches 15 break; 16 default: 17 System.out.println("Unknown season."); 18}

Output:

Cold and dry.

⚠️ String switch is case-sensitive. "winter" does NOT match case "Winter". Always ensure the case in your switch matches the exact case of the input string.

Java
1switch (season.toLowerCase()) { // normalize to lowercase first 2 case "spring": ... 3 case "summer": ... 4}

The Modern Switch Expression (Java 14+)

Java 14 introduced a cleaner switch syntax that eliminates break, prevents fall-through by design, and can return a value directly.

Traditional switch (old way):

Java
1String day = "MONDAY"; 2String type; 3 4switch (day) { 5 case "MONDAY": 6 case "TUESDAY": 7 case "WEDNESDAY": 8 case "THURSDAY": 9 case "FRIDAY": 10 type = "Weekday"; 11 break; 12 case "SATURDAY": 13 case "SUNDAY": 14 type = "Weekend"; 15 break; 16 default: 17 type = "Unknown"; 18} 19 20System.out.println(type);

Switch expression (modern way):

Java
1String day = "MONDAY"; 2 3String type = switch (day) { 4 case "MONDAY", "TUESDAY", "WEDNESDAY", "THURSDAY", "FRIDAY" -> "Weekday"; 5 case "SATURDAY", "SUNDAY" -> "Weekend"; 6 default -> "Unknown"; 7}; 8 9System.out.println(type); // Weekday

What changed:

FeatureTraditional switchSwitch Expression (Java 14+)
break required✅ Yes❌ No
Fall-through possible✅ Yes (bug risk)❌ No (by design)
Multiple values per case❌ Stack empty casescase A, B, C ->
Returns a value❌ No✅ Yes (assign directly)
Arrow syntax->

More switch expression examples:

Java
1// Grade based on marks 2int marks = 82; 3 4String grade = switch (marks / 10) { 5 case 10, 9 -> "A"; 6 case 8 -> "B"; 7 case 7 -> "C"; 8 case 6 -> "D"; 9 default -> "F"; 10}; 11 12System.out.println("Grade: " + grade); // Grade: B
Java
1// Number of days in a month 2int month = 4; 3 4int days = switch (month) { 5 case 1, 3, 5, 7, 8, 10, 12 -> 31; 6 case 4, 6, 9, 11 -> 30; 7 case 2 -> 28; 8 default -> throw new IllegalArgumentException("Invalid month: " + month); 9}; 10 11System.out.println(month + " has " + days + " days."); // 4 has 30 days.

💡 Use the modern switch expression when you can. It is less error-prone (no accidental fall-through), more concise, and directly returns values. If you are on Java 14 or later — and most projects are — prefer -> over the traditional colon syntax.

switch vs if/else — When to Use Which

switch vs if/else — WHEN TO USE EACH Use switch when... ✅ Checking ONE variable ✅ Against EXACT values (not ranges) ✅ Many possible values (5+) ✅ int, char, String, enum switch (day) { case 1: ... } switch (color) { case "red": ... } Use if/else when... ✅ Range checks (x > 10) ✅ Multiple variables ✅ Complex conditions (&&, ||) ✅ double, float, boolean if (score >= 60) { ... } if (a > 0 && b < 10) { ... }
Java
1// Use switch — one variable, exact values: 2switch (command) { 3 case "start" -> startEngine(); 4 case "stop" -> stopEngine(); 5 case "pause" -> pauseEngine(); 6 default -> System.out.println("Unknown command"); 7} 8 9// Use if/else — range check, not exact value: 10if (temperature < 0) { 11 System.out.println("Freezing"); 12} else if (temperature < 20) { 13 System.out.println("Cold"); 14} else { 15 System.out.println("Warm"); 16}

A Complete Example — Menu-Driven Calculator

Java
1import java.util.Scanner; 2 3public class Calculator { 4 public static void main(String[] args) { 5 6 Scanner scanner = new Scanner(System.in); 7 8 System.out.print("Enter first number: "); 9 double a = scanner.nextDouble(); 10 11 System.out.print("Enter second number: "); 12 double b = scanner.nextDouble(); 13 14 System.out.print("Enter operator (+, -, *, /): "); 15 String op = scanner.next(); 16 17 double result = switch (op) { 18 case "+" -> a + b; 19 case "-" -> a - b; 20 case "*" -> a * b; 21 case "/" -> { 22 if (b == 0) { 23 System.out.println("Error: division by zero."); 24 yield 0; // 'yield' returns a value from a block in switch expression 25 } 26 yield a / b; 27 } 28 default -> { 29 System.out.println("Unknown operator: " + op); 30 yield 0; 31 } 32 }; 33 34 System.out.println(a + " " + op + " " + b + " = " + result); 35 scanner.close(); 36 } 37}

Sample output:

Enter first number: 15 Enter second number: 4 Enter operator (+, -, *, /): / 15.0 / 4.0 = 3.75

💡 yield is used inside a block ({ }) in a switch expression to return a value. When the case uses -> with a single expression, yield is not needed. When the case needs multiple statements, wrap them in { } and use yield to return the result.

Common Mistakes

1. Forgetting break — accidental fall-through

Java
1switch (day) { 2 case 1: 3 System.out.println("Monday"); // runs 4 // ← missing break! 5 case 2: 6 System.out.println("Tuesday"); // also runs — unintended! 7}

Fix: add break at the end of every case, or use the modern -> syntax.

2. Using a variable as a case value

Java
1int limit = 100; 2 3switch (x) { 4 case limit: // ❌ error — case values must be constants 5 ... 6} 7 8switch (x) { 9 case 100: // ✅ literal constant 10 ... 11}

3. Using unsupported types

Java
1double price = 9.99; 2switch (price) { ... } // ❌ error — double not supported 3 4boolean flag = true; 5switch (flag) { ... } // ❌ error — boolean not supported 6 7long big = 100L; 8switch (big) { ... } // ❌ error — long not supported

Supported types: int, byte, short, char, String, enums (and their wrapper types Integer, Character, etc.)

4. Case-sensitive String matching

Java
1String input = "winter"; 2 3switch (input) { 4 case "Winter": // ❌ no match — "winter" ≠ "Winter" 5 System.out.println("Cold"); 6} 7 8switch (input.toLowerCase()) { 9 case "winter": // ✅ normalize first 10 System.out.println("Cold"); 11}

5. Missing default

Java
1switch (status) { 2 case "active": System.out.println("Running"); break; 3 case "paused": System.out.println("Paused"); break; 4 // What if status is "error" or "unknown"? Silent — nothing happens 5}

Always include default to handle unexpected values explicitly.

Quick Reference

Java
1// Traditional switch 2switch (variable) { 3 case value1: 4 // code 5 break; 6 case value2: 7 case value3: // fall-through — both run this block 8 // code 9 break; 10 default: 11 // code if no match 12} 13 14// Switch expression (Java 14+) — preferred 15String result = switch (variable) { 16 case value1 -> "result1"; 17 case value2, value3 -> "result2"; // multiple values — clean syntax 18 default -> "default result"; 19}; 20 21// Switch expression with block and yield 22int output = switch (x) { 23 case 1 -> 10; 24 case 2 -> { 25 int temp = x * 5; 26 yield temp + 1; // return value from block 27 } 28 default -> 0; 29};

The 3 Things to Remember From This Page

  1. Always add break in traditional switch — or use the modern -> syntax which prevents fall-through by design. Forgetting break is the most common switch bug.
  2. switch only works with exact values, not ranges — use switch for day == 3, use if/else for score >= 60. Trying to use switch for range checks won't work.
  3. Prefer the modern switch expression (->) when on Java 14+. It's shorter, has no fall-through risk, supports multiple values per case with commas, and can return a value directly.

Summary

  • switch matches one expression against a list of exact case values
  • break exits the switch — without it, execution falls through to the next case
  • default runs when no case matches — always include it
  • Fall-through is usually a bug (missing break), but can be intentional for grouping cases
  • switch supports: int, byte, short, char, String, enums (not double, float, long, boolean)
  • String switch is case-sensitive — normalize with .toLowerCase() if needed
  • Modern switch expression (->, Java 14+): no break, no fall-through, multiple values per case, returns a value
  • yield returns a value from a block { } inside a switch expression
  • Use switch for exact value matching on one variable. Use if/else for ranges, multiple variables, and complex conditions.

What to Read Next

TopicLink
if / else — conditional statementsif / else / else-if →
for loop — repeating code a fixed number of timesfor Loop →
Enums — the perfect companion for switchEnums →
Switch expressions in depth (Java 14–21)Switch Expressions →
Operators — comparison operators used in switchOperators →
switch Statement | DevStackFlow