Switch Case in Java with Examples
Switch statements in Java enable execution of different code blocks based on the value of an expression. They provide an alternative to multiple if-else statements and can be used when an expression can have numerous possible values.
The switch statement in Java is a control statement that allows you to choose between several blocks of code to execute, depending on the value of an expression. Here is the basic syntax for a switch statement:
switch (expression) { case value1: // code to be executed if expression == value1 break; case value2: // code to be executed if expression == value2 break; ... default: // code to be executed if expression does not match any of the values}
The expression in a switch statement must be of a type that can be compared to the values specified in the case labels. This includes the following types:
- byte
- short
- int
- char
- String (since Java 7)
- enum (since Java 5)
Here is an example of a switch statement that uses an int value as the expression:
int dayOfWeek = 3;switch (dayOfWeek) { 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; default: System.out.println("Invalid day of the week");}
This code will output “Wednesday” to the console.
A default case is used to execute a block of code if the expression does not match any of the values specified in the case labels. This is optional, but it is a good idea to include it in your switch statement to handle unexpected values of the expression.
NOTE: It is important to include the break statement at the end of each case block. It prevents the code from falling through to the next case block. If you omit the break statement, all of the code in the following case blocks will be executed until a break statement is encountered.
Let’s take an example of a switch statement with missing break statement in some of the case blocks:
int num = 3;switch (num) { case 1: System.out.println("One"); case 2: System.out.println("Two"); case 3: System.out.println("Three"); case 4: System.out.println("Four"); case 5: System.out.println("Five"); default: System.out.println("Invalid number");}
Output:
Three Four Five Invalid number
You got this output because the break statement is not used in all of the case blocks. So the code executes the next case block until it reaches a break statement or the end of the switch statement.
Key Point to Remember While Using Switch Statement in Java
- The expression in switch statement must be of byte, short, int, char, String, or enum type
- case labels must be literals or constants and unique within switch statement
- break statement is used to terminate a case block and move to next statement after switch statement
- default case handles unexpected values
- Switch statement is an alternative to long if-else statements, making code more readable and easy to maintain
- Multiple case labels can be used with same block of code using comma separation.
Best-suited Java courses for you
Learn Java with these high-rated online courses
Applications of Switch Case
- Menu systems: Use a switch case statement to create a menu system that allows a user to select options from a list.
- Input validation: Validate input from a user. For example, you might use a switch case statement to make sure that a user has entered a valid option.
- Conditional execution: Execute different blocks of code based on different conditions.
- Enforcing business rules: You might use a switch case statement to make sure that a user is only allowed to access certain features if they have the appropriate permissions.
- Mapping Values: Convert a set of numeric values to their corresponding string value.
- Handling errors: Use a switch case statement to handle different types of input validation errors.
Case Study: Enforcing business Rule Using Switch Case
Problem: You are building a software application that has different levels of access for different user roles. Admins should be able to access all features, managers should be able to access certain features, and employees should be able to access certain features.
Objective: Write a Java program that prompts the user for their role and the feature they want to access, and then uses a switch case statement to enforce the following business rules:
- Admins can access all features.
- Managers can access the “sales data” and “employee data” features.
- Employees can access the “time clock” feature.
If the user’s role or the feature they want to access is not recognized, access should be denied.
Input:
- A string representing the user’s role (e.g. “admin”, “manager”, “employee”)
- A string representing the feature the user wants to access (e.g. “sales data”, “employee data”, “time clock”)
Output:
- A string indicating whether access is granted or denied (e.g. “Access granted.”, “Access denied.”)
Code:
import java.util.Scanner;
public class BusinessRuleEnforcer { public static void main(String[] args) { Scanner scanner = new Scanner(System.in); System.out.print("Enter your role: "); String role = scanner.nextLine(); System.out.print("Enter the feature you want to access: "); String feature = scanner.nextLine();
switch (role) { case "admin": // Admins can access all features System.out.println("Access granted."); break; case "manager": // Managers can only access certain features switch (feature) { case "sales data": case "employee data": System.out.println("Access granted."); break; default: System.out.println("Access denied."); break; } break; case "employee": // Employees can only access certain features switch (feature) { case "time clock": System.out.println("Access granted."); break; default: System.out.println("Access denied."); break; } break; default: // Unrecognized role System.out.println("Access denied."); break; } }}
In this example, the program prompts the user to enter their role and the feature they want to access. It then uses a switch case statement to enforce the following business rules:
- Admins can access all features.
- Managers can access the “sales data” and “employee data” features.
- Employees can access the “time clock” feature.
Access is denied if the user’s role or the feature they want to access is not recognized. You can modify this code by adding additional features in the cases.
Conclusion
In summary, the switch statement in Java makes your code more efficient and readable. It is a good alternative to using long chains of if-else statements. Switch statements allow using the same block of code for multiple options.
Experienced AI and Machine Learning content creator with a passion for using data to solve real-world challenges. I specialize in Python, SQL, NLP, and Data Visualization. My goal is to make data science engaging an... Read Full Bio