Switch Statements
We use switch statements to execute different parts of code dependant on our observed value. Switch statements are a great way to make multiple choice conditionals easier to read, the same effect can be achieved by an if
statement however good quality code needs to be readable as well as functional.
String role = "admin";switch (role){ case "admin": System.out.println("Congrats, you are an admin!"); break; case "moderator": System.out.println("Moderate away!"); break; default: System.out.println("You're a guest");}
Case, Break and Default
Section titled “Case, Break and Default”A case
in a switch
statement is similar to an if
statement, but it functions by comparing a variable (or expression) against a set of predefined constant values. We use the switch
statement to evaluate a variable that may have multiple possible values, and then the case
checks for specific values that are important to execute the corresponding code. Each case
represents a fixed, static value that the expression is compared against. The case
labels themselves are rigid in that they can only be set to constant values and cannot be variables, expressions, or dynamic values (such as the result of a function call). This means the values within the case
statements must be constant literals or enumerated types.
In Java once a case is matched the preceding code block will execute, It is important to note that each code block will require a break;
in order for the program to exit the switch
statement. Without a break;
the program will continue executing the next case blocks code - this practice is called a fall-through and may be intentional in some cases.
Default
Section titled “Default”Providing a default
case in a switch statement is considered good practice. It ensures that the program will execute a code block when none of the case
labels match the value of the switch
expression. This provides a fallback action, which is particularly useful for handling unexpected or invalid values.
The default
case is typically placed at the bottom of the switch
block, as it serves as the “catch-all” for any unmatched values.