Other than if/if-else/if-else if-else and the ternary operator, there is yet another common and important conditional expression in Java that every good programmer should be aware of: the switch statement.
switch looks like this
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;
case 4:
System.out.println("Thursday");
break;
case 5:
System.out.println("Friday");
break;
case 6:
System.out.println("Saturday");
break;
case 7:
System.out.println("Sunday");
break;
default:
System.out.println("Invalid day");
}
A few things are important to notice:
- You work on the different states of a variable (inside the switch parentheses), which must have been declared and initialized before the switch
- You differentiate each of those states as a “case,” after which you put a colon and the behavior you want
- You don’t use braces to enclose multiple statements, like you would in an if, else, or loop. You instead use “break” to determine when you’re done giving behavior for a specific case
- If a “break” is ever omitted, Java will “fall through” and continue executing either until a break, return, or the end of the switch
- For all other cases besides the ones you explicitly label in this construction, you can define a fallback behavior with the “default” part of the statement. Typically, this appears last, as above, but technically, Java's specifications allow it to be placed in any order among the different possible branches of the switch statement.
- Just like you can nest if-statements and loops, you can nest switch statements
You won’t see switch statements as often as you will if
statements, but it’s still important to know how to build them, and that every
idea expressible by one form is expressible by the other. Happy switching!