Java Selection Statements: switch-case Statements
switch-case Statements
A switch statement is an alternative to the if-else statement where it directly compares one variable to another. It is a multi-way branch statement and provides an easy way to execute code blocks based on the value of the expression.
This is important: Switch statements can have expressions of type byte, short, int, and char. Since JDK7, they also work with enumerated (enum) types, the String class and Wrapper classes.
The general syntax is:
switch (expression) {
case value1:
statement1;
break;
case valueN:
statementN;
break;
default:
statementDefault;
}
Let’s break this down line by line.
The switch statement starts with the switch keyword followed by the name of the variable or expression to be evaluated and opening curly bracket:
switch (variable or expression) {
Then, the first of possible cases are tested, the value will be compared to the current value of the variable or expression above, if they match the code block will be executed, if not Java will move onto the next case:
case value1;
statement1;
The break forces an exit to prevent Java from running into the next case. This is optional and will not cause an error but omitting it will cause execution to continue on into the next case:
break;
Then, you can have as many cases as you need, just remember to include a break at the end of each:
case valueN:
statementN;
break;
The default case is will execute if none of the above cases are a match but this is an optional component:
default:
statementDefault;
Finally, terminate your Switch Statement with a close curly bracket:
}
Let’s see how this might work in practice. Imagine there is a console in a College that when a user enters the name of a tutor it will display their contact information like their name, extension and room number so that they can be easily found by students. We’ll use a switch statement to solve this problem which will require a variable to test within the switch statement:
String tutorName = "Harry"; switch (tutorName) { case "James": System.out.println("James: Ext. 2231, Room 12a"); break; case "Harry": System.out.println("Harry: Ext. 3665, Room 56"); break; case "Jane": System.out.println("Jane: Ext. 5448, Room 11b"); break; default: System.out.println("Tutor not found"); }
The output for this code should be Harry’s contact details:
run: Harry: Ext. 3665, Room 56 BUILD SUCCESSFUL (total time: 0 seconds)
If we failed to include the break statement we would have seen Jane’s contact details too, do you know why?
Try changing the tutor name the see if you get an expected result. Then try adding more tutor names and contact details.
If none of the cases matched the name input by the user then the default code block would be executed. Test that this is the case but changing the value of tutorName to one that does not exist in the code.