So you learned if-else. That works great when you have two or three conditions. But what if you have ten? Or fifteen? Writing that many if-else statements gets messy fast. That is where switch comes in.
The switch statement lets you compare a single value against multiple possible matches. It is cleaner, more readable, and frankly, more satisfying to write.
Basic switch
You give switch a variable, and it checks it against each case.
When it finds a match, it runs the code in that case.
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;
case 4:
System.out.println("Thursday");
break;
case 5:
System.out.println("Friday");
break;
default:
System.out.println("Weekend");
}
}
}
Break and Default
Two important things about switch. First, the break keyword stops
the switch from checking the rest of the cases. If you forget it, Java keeps
running code from the next case too โ that is called fall-through.
Second, default is the catch-all. If none of the cases match,
the default block runs. It is like the final else in an if-else chain.
public class Main {
public static void main(String[] args) {
String color = "red";
switch (color) {
case "red":
System.out.println("Stop");
break;
case "yellow":
System.out.println("Slow down");
break;
case "green":
System.out.println("Go");
break;
default:
System.out.println("Unknown color");
}
}
}
Notice that switch works with strings too, not just numbers. That is a nice feature that makes your code much more readable.