A switch statement is a decision-making structure in which a single value is evaluated and flow is redirected to the first matching case statement.
If no such case statement is found that matches the value, an
optional default
statement will be called.
If no such default option is available, the entire switch statement will be skipped.
A switch statement has a target variable that is not evaluated until runtime.
Data types supported by switch statements include the following:
int and Integer byte and Byte short and Short char and Character int and Integer String enum values
The boolean and long, and their associated wrapper classes, are not supported by switch statements.
The values in each case statement must be compile-time constant values in the same data type as the switch value.
We can use only literals, enum constants, or final constant variables of the same data type.
final constant is the variable marked with the final modifier and initialized with a literal value in the same expression.
The following code uses the day of the week, with 0 for Sunday, 1 for Monday, and so on:
int dayOfWeek = 5; switch(dayOfWeek) { default: System.out.println("Weekday"); break; case 0: System.out.println("Sunday"); break; case 6: System.out.println("Saturday"); break; }
With a value of dayOfWeek of 5, this code will output:
Weekday
There is a break statement at the end of each case and default section.
break statement terminates the switch statement and returns flow control to the enclosing statement.
There is no requirement that the case or default statements be in a particular order.
The following code shows a switch statement without break
statement.
public class Main{ public static void main(String[] argv){ int dayOfWeek = 5; switch(dayOfWeek) { case 0: System.out.println("Sunday"); default: System.out.println("Weekday"); case 6: System.out.println("Saturday"); break; } } }
For the given value of dayOfWeek, 5, the code will jump to the default block and then execute all of the proceeding case statements in order until it finds a break statement or finishes the structure:
Weekday Saturday
The order of the case and default statements is important since placing the default statement at the end of the switch statement would cause only one word to be output.
If the value of dayOfWeek was 6 the output would be:
Saturday
Even though the default block was before the case block, only the case block was executed.
If you recall the definition of the default block, it is only branched to if there is no matching case value for the switch statement, regardless of its position within the switch statement.
Finally, if the value of dayOfWeek was 0, all three statements would be output:
Sunday Weekday Saturday