


The default statement is meant to execute when there is no match between the values of the variable and the cases. Optional default case: default case value is optional.If a case is matched and there is no break statement mentioned, subsequent cases are executed until a break statement or end of the switch statement is encountered. Optional Break Statement: Break statement is optional in Java's switch statement.Primitives are allowed with their wrapper types. Allowed Types: The Java switch expression must be of int, long, byte, short, enums and String type.No duplicates: No two cases in a switch statement should be of same value.Also, it must be of the same type as switch expression. No variables: The case value in switch statement must be a literal or constant.Important Points about Java's switch statement: Let’s quickly go through some standard rules for writing switch cases. Now if the values do not match it goes to the next case and follows the same steps and if none of the case values matches the value of the variable, it executes the default statement.Next, it goes to Case 1, compare the values, if the value matches it goes on to execute the Statement 1 and then it executes Break statement which brings the switch block to end so no more case testing is done.It starts with the Switch Expression where the variable is placed whose value is to be checked against case values.In such scenarios, when a case passes, all the subsequent cases execute as well until a break statement or the end of the switch block is encountered. The switch case is called a fall-through statement when we miss out break statements in switch cases. In this scenario, suppose the day variable is given the value 9 then all the cases will be checked and since equality conditions cannot be achieved with this value, the default statement will get executed at the end.
#Java switch statement code#
The execution of any more code within the switch-case block is seized and case testing/comparison is stopped.Īlso, the default statement is executed when there is no single comparison that checks out which means the value of variable and the case value doesn’t match in of the any cases. When the Java program reads the break statement it comes out of the switch block immediately with no further comparisions. Significant of Break & Default Statements The break statement in the fourth case breaks out of the switch statement.Since day = 4, it matches the fourth case value and Day 4: Thursday is printed. The value of the day variable is compared with each of the case values.
