Java Switch Statements
Rather than employing numerous if…else statements, you can utilize the switch statement.
This statement chooses one of several code blocks to execut:
Syntax
switch(expression) {
case x:
break;
case y:
break;
default:
}
|
Here’s how it operates:
- The switch expression undergoes evaluation once.
- It compares the value of the expression with each case’s values.
- Upon finding a match, the corresponding block of code executes.
- The keywords break and default are optional and will be further explained later in this chapter.
The following example utilizes the weekday number to determine the weekday name:
Example
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;
}
// Outputs "Thursday" (day 4)
|
The break Keyword
Upon encountering a break keyword in Java, the program exits the switch block.
This will halting the execution of further code and case testing within the block.
Once a match is found and the task is completed, it’s time to implement a break. Further testing is unnecessary at this point.
A break can significantly save execution time by effectively bypassing the execution of all remaining code within the switch block.
|
The default Keyword
The default keyword designates a piece of code to execute if there is no match with any case.
Example
int day = 4;
switch (day) {
case 6:
System.out.println("Today is Saturday");
break;
case 7:
System.out.println("Today is Sunday");
break;
default:
System.out.println("Looking forward to the Weekend");
}
|
If the default statement is positioned at the end of a switch block, a break statement is unnecessary. |