Switch Case in Java
Video Tutorial
Overview
Switch statement in Java is used to select one of the many code blocks to be executed. The value of the expression in switch statement is compared with the values of each case.
If there is a match, the associated block of code is executed. Switch case in Java is fall-through which means it executes all the cases after the first match if a break statement is not encountered.
Introduction
The switch case statement is the comparison between a variable and its possible values i.e. the variable is checked against all its possible values for equality. The possible values constitute different cases and the variable is switched to every case one by one to check for equality, hence it’s called a switch-case statement.
Syntax
Let us understand the usage of Switch case in Java programmatically.
Example
Consider the code snippet given below:
Output:
Explanation:
- The value of the day variable is compared with each of the case values. Since day = 4, it matches the fourth case value and Day 4: Thursday is printed.
- The break statement in the fourth case breaks out of the switch statement.
Significant of Break & Default Statements
When the Java program reads the break statement it comes out of the switch block immediately with no further comparisions. The execution of any more code within the switch-case block is seized and case testing/comparison is stopped.
Also, 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. 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.
Fall-through Statement
The switch case is called a fall-through statement when we miss out break statements in switch cases. 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.
Example:
Output:
Explanation:
As it is clear, after the value of day variable matches the case with value 4, all subsequent cases till case 7 are executed until a break statement is encountered in case 7.
Flowchart of Switch case in Java
- It starts with the Switch Expression where the variable is placed whose value is to be checked against case values.
- 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.
- 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.
Important rules for Switch case in Java
Let’s quickly go through some standard rules for writing switch cases.
Important Points about Java's switch statement:
- No variables: The case value in switch statement must be a literal or constant. Also, it must be of the same type as switch expression.
- No duplicates: No two cases in a switch statement should be of same value. Otherwise, compilation error is thrown.
- Allowed Types: The Java switch expression must be of int, long, byte, short, enums and String type. Primitives are allowed with their wrapper types.
- Optional Break Statement: Break statement is optional in Java's switch statement. 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 default case: default case value is optional. The default statement is meant to execute when there is no match between the values of the variable and the cases. It can be placed anywhere in the switch block according to the required result.
Interesting Example
If the case with the matching value as variable’s value is after the default statement, that case statement will execute without the default statement executing even if you put break after default. But this only happens when the case after default has the same value with variable value. If the case value after default does not match with the variable value (i.e. no match at all scenario) then the default case is evaluated.
Code:
Output:
Explanation:
As explained above, since day value is matching with case 4, default statement is not executed, instead case 4 statement is executed. This is in accordance with the definition of default case definition.
Switch case in Java with Strings
Java allows us to use switch statements with strings, that means we can take a variable of string data-type and apply switch-case with string literals as cases.
Output:
Explanation:
In the above code snippet we have taken two variables, day and marksRange, we are making comparisions between day and case values and when the case and variable value matches, the value of review changes according to the particular case. After the switch case block, the marksRange variable is printed.
Nested Switch Statement in Java
A nested switch statement refers to a scenario where a switch statement is used inside another switch statement. Basically, it is switch statement within a switch statement.
Example:
Output:
Java Enum in Switch Statement
Enum or enumerator’s purpose is to represent a group, a set of known constants. For example, 4 seasons in a year, planets in the solar system or house numbers in a gated colony.
In our example, we use it for a set of drinks on the menu. Using the enum keyword, we can define a new data-type.
Did you know?
In Java, enums can also have methods, constructors and variables and they can be declared inside or outside the Main class.
Let’s dive into an example to understand better.
Output:
Explanation:
- In the above code snippet, Month is our enum representing the set of months.
- First, we declared an enum outside the main method, then inside the main method, we created an object month and assigned it a constant from the Month enum.
- Every case value which is enum constants will be compared against the month value and the subsequent statement will be executed displaying your month selection.
Java Wrapper in Switch Statement
The wrapper class in Java allows us to convert primitive data types into objects. We can use Byte, Integer, Short and Long variables with wrapper classes in switch statements in Java.
Example:
Output:
Explanation: In the above code snippet, Integer is an object as it is converted from primitive data type (int) to object (Integer). The object value is checked against case values and it follows the same process.
Conclusion
- The Switch case in Java is the comparison between a variable and its possible values.
- Break statement is used to come out of the switch block immediately without any further comparisons.
- Default statement is executed only when there is no case with value same as the variable value.
- Switch case is called a fall-through statement when we miss out break statements in switch cases.
- We can nest one switch statement within another switch statement with independent variable values.
- We can use enum and wrapper classes in switch statements in Java.