AI Hints
Home›Java Tutorial›Logical Operators, The Ternary Operator and switch
Java · Lesson 33 of 120

switch

Choosing from many cases.

⏱ 2 min read▶ Video at 42:44🎓 Free
Watch this lesson in the Java courseWatch on YouTube ↗Full Java course

When one value can match many different cases, like a day number, or a menu choice, a switch statement can be clearer than a long chain of else ifs.

  • One value
  • Many cases
  • Clearer than else if

A classic switch

Switch looks at the value of day. Java jumps to the matching case. Break stops the switch, so nothing else runs. Default runs when no case matches. Day is three. Run it. Wednesday.

Main.javajava
public class Main {
    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("Another day");
        }
    }
}
Output
Wednesday

Forgetting break

What if we forget the breaks? Day is two. Run it. Tuesday, Wednesday, and another day all print! Without break, Java falls through, into every case below. That's a classic bug.

Main.javajava
public class Main {
    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");
            default:
                System.out.println("Another day");
        }
    }
}
Output
Tuesday
Wednesday
Another day

Summary

Switch jumps to the matching case. Use break, or it falls through into the next cases. Next, a newer, safer kind of switch.

Key takeaways
  • switch (value)
  • case, break
  • default
Next up: Switch Expressions — modern, safer switch