java / beginner
Snippet
The Switch Statement
The switch statement allows you to select one of many code blocks to be executed based on the value of a variable. It is often cleaner than multiple nested if-else statements.
snippet.java
1
2
3
4
5
6
int day = 2;switch (day) {case 1: System.out.println("Monday"); break;case 2: System.out.println("Tuesday"); break;default: System.out.println("Other day");}
Breakdown
1
switch (day)
Starts the switch block evaluating the variable 'day'.
2
case 1:
Defines the code to run if day is equal to 1.
3
break;
Terminates the switch block so execution doesn't fall through to the next case.