Loading lessons...
Java Switch
Java Switch
The switch statement picks one of many code blocks to run. It is a cleaner way to test a value against many cases.
Switch syntax
int day = 4;
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("Looking forward to the weekend");
}
How it works
- The switch expression is evaluated once.
- It is compared to each
case. - When a match is found, that block runs until a
break. defaultruns when no case matches.
The break keyword
break stops the switch from running the remaining cases. Without break, Java keeps running the next case (this is called fall through).
Default
The default block is optional. It is the fallback when no case matches.
TL;DR
switchtests one value against multiplecaselabels.- Each case should end with
break. defaultruns when no case matches.