The switch Statement
switch is a tidy way to pick one of many options based on a single value.
What you will learn
- Write a switch statement
- Use case, break and default
- Know when switch beats a long if chain
One value, many cases
When you are checking the same variable against many fixed values, a long if / else if chain gets messy. A switch is cleaner: list each value as a case.
int day = 3;
String name;
switch (day) {
case 1: name = "Monday"; break;
case 2: name = "Tuesday"; break;
case 3: name = "Wednesday"; break;
case 4: name = "Thursday"; break;
case 5: name = "Friday"; break;
default: name = "Weekend";
}
System.out.println("Day " + day + " is " + name);Note: Output:
Day 3 is Wednesday
Java jumps to case 3, sets the name, and break stops it there. default runs when no case matches (here, days 6 and 7).
The important parts
case— a value to match against the switch variable.break— stops the switch. Without it, Java keeps running into the next case (called fall-through).default— the catch-all, like the finalelse. It runs when nothing else matched.
Watch out: Do not forget break. If you leave it out, Java falls through and runs the next case too — a sneaky bug. (Sometimes fall-through is wanted, but as a beginner, always add break.)
switch works on text too
A switch is not just for numbers — it can match a String as well. This is handy for simple menus where the user types a word like a command.
String command = "stop";
switch (command) {
case "start": System.out.println("Starting..."); break;
case "stop": System.out.println("Stopping..."); break;
case "pause": System.out.println("Paused."); break;
default: System.out.println("Unknown command.");
}Note: Output:
Stopping...
The value of command is "stop", so Java jumps to case "stop" and prints Stopping... Matching text works exactly like matching numbers — each case is one possible value of the switch variable.
Tip: Newer Java has an arrow form: case 3 -> name = "Wednesday"; which needs no break. The classic form shown here works in every version, so it is the safest to learn first.
Q. What does break do inside a switch?
break, Java falls through into the following cases. break exits the switch once a case has run.✍️ Practice
- Write a switch that turns a number 1 to 5 into a star rating message.
- Add a
defaultcase that prints Unknown for any other number.
🏠 Homework
- Build a tiny menu: read a number 1 to 3 and use switch to print Add, View or Quit.