Switch Statement In Java | Working, Uses & More (+Code Examples)
The switch statement in Java is a control structure that allows you to execute one of several possible blocks of code based on the value of an expression. It's often used when you have multiple conditions to check, making the code cleaner and easier to read compared to using multiple if-else statements. In a switch, the expression is evaluated, and the program jumps to the corresponding case that matches the value. If none match, an optional default case is executed.
In this article, we'll cover the basic syntax, explore different ways to use the switch statement, and look at practical code examples to help you understand when and how to use it effectively in your Java programs.
What Is Switch Statement In Java?
In Java programming, the switch statement is a control flow statement that allows us to execute one out of many blocks of code based on the value of an expression. It is an alternative to using multiple if-else statements when we need to compare a single variable to a set of constants. The switch statement simplifies complex conditional logic and enhances code readability.
Syntax Of Switch Statement In Java
switch (expression) {
case constant1:
// Code block to execute if expression equals constant1
break;
case constant2:
// Code block to execute if expression equals constant2
break;
// More cases as needed
default:
// Code block to execute if expression doesn't match any case
}
Here:
- Expression: The value or variable being evaluated (e.g., int, char, String).
- Case Labels: Constants to compare with the expression (e.g., case 1:, case 'A':).
- Code Block: The code executed if a case matches the expression.
- Break Statement: Exits the switch statement after a case is executed (optional but recommended).
- Default Case: Optional; runs if no case matches the expression.
Working Of The Switch Statement In Java
The switch statement in Java language works by evaluating a given expression and comparing its value against the constant values (case labels) defined inside the switch block. Here's how it functions step by step:
- Expression Evaluation: The expression provided in the switch statement is evaluated first. This expression can be of type int, char, String, or an enumerated type.
- Case Matching: The evaluated expression is then compared with the values of each case label. If a match is found:
- The corresponding block of code associated with that case is executed.
- The flow moves to the break statement (if present) to exit the switch block.
- Break Statement:
- If a break statement is encountered, the execution of the switch statement is terminated, and control passes to the next statement after the switch.
- If no break is used, the program continues executing the next case block (this is known as "fall-through").
- No Match (Default Case):
- If none of the case labels match the expression, and if a default case is provided, the code inside the default block is executed.
- The default case is optional and serves as a fallback option if no match is found.
For Example:
int number = 2;
switch (number) {
case 1:
System.out.println("One");
break;
case 2:
System.out.println("Two");
break;
case 3:
System.out.println("Three");
break;
default:
System.out.println("Unknown");
}
Here:
- The expression number is evaluated.
- Since number = 2, it matches the case 2.
- The code inside case 2 is executed: "Two" is printed.
- The break statement terminates the switch statement.
- If number were 4, the default case would be executed, printing "Unknown".
Example Of Switch Statement In Java
Let’s look at a simple Java program that uses a switch statement to print the name of the day based on an integer value.
Code Example:
Output (set code file name as SwitchExample.java):
Wednesday
Explanation:
In the above code example-
- First, we declare an integer variable day and set it to 3. This represents the day of the week, with 1 for Monday, 2 for Tuesday, and so on. For our example, day = 3 corresponds to Wednesday.
- Next, we use the switch statement to evaluate the value of the day variable. The switch checks the value of day against different case values.
- The first case checks if day equals 1. If it does, the program prints "Monday". After that, the break statement is used to exit the switch block, preventing further evaluation of other cases.
- Similarly, if day equals 2, the program prints "Tuesday" and exits the switch block after the break.
- If the value of day is 3, as in our example, the program enters the case 3 block and prints "Wednesday". Once the statement is executed, the break ensures that the switch block terminates.
- This process continues for each of the case values (4 through 7), printing the respective day names (Thursday, Friday, Saturday, and Sunday) if the value of day matches the case.
- If none of the cases match the value of day, the default case is executed. In our example, if the value of day were outside the range of 1 to 7, it would print "Invalid day", indicating an invalid input.
- Finally, the program ends after the switch block completes its execution.
Explore this amazing course and master all the key concepts of Java programming effortlessly!
Java Switch Statement With String
In Java, starting from Java 7, you can use a String expression in a switch statement. This allows you to compare a string value against multiple string constants, making it useful for situations where you need to handle different string values more efficiently than with multiple if-else statements.
How It Works:
- The expression inside the switch is evaluated, and its value is compared to each case label.
- Each case contains a string constant.
- If a match is found, the corresponding block of code is executed.
- If no match is found, the default block (if provided) is executed.
- The break statement is used to exit the switch block after the matching case has executed.
Code Example:
Output (set code file name as SwitchWithString.java):
Good Morning!
Explanation:
In the above code example-
- We start by declaring a string variable timeOfDay and initialize it with the value "morning". This is the input that determines the greeting message, and we can change this value to test different cases (like "afternoon", "evening", or "night").
- Next, we use a switch statement to evaluate the value of the timeOfDay variable. The switch checks the value of timeOfDay against the various case options.
- The first case checks if timeOfDay is equal to "morning". If this condition is true, the program prints "Good Morning!" and exits the switch block using the break statement to prevent further case evaluations.
- Similarly, if timeOfDay equals "afternoon", the program will print "Good Afternoon!" and then exit the switch block after the break.
- If timeOfDay is "evening", the program will print "Good Evening!" and terminate the switch statement with a break.
- The case for "night" checks if the value of timeOfDay is "night". If it matches, the program will print "Good Night!" and then exit the switch block.
- If timeOfDay doesn't match any of the specific cases (for example, if the value is something like "noon" or any other unhandled input), the default case is executed. In this case, the program will print "Hello!" as a fallback message.
- The program ends after the switch block has completed its execution.
Java Nested Switch Statements
A nested switch statement in Java is a switch statement inside another switch statement. This allows you to handle more complex conditions by checking multiple levels of cases. The outer switch evaluates one expression, and if a specific case matches, an inner switch can evaluate another expression within that block.
How It Works:
- The outer switch evaluates its expression.
- Based on the outer switch case, the corresponding block is executed.
- If the outer block contains a nested switch, it will evaluate another expression inside that block.
- You can use break statements to exit each switch statement properly.
Code Example:
Output (set code file name as NestedSwitchExample.java):
Wednesday:
Good Morning, Wednesday!
Explanation:
In the above code example-
- We start by declaring an integer variable day and a string variable time. The day variable holds a number (in this case, 3) corresponding to a day of the week (1 = Monday, 2 = Tuesday, 3 = Wednesday, and so on). The time variable is set to "morning" initially, but we can change it to test different greetings based on the time of day.
- The outer switch statement checks the value of day. If day equals 1, the program prints "Monday:". If day is 2, it prints "Tuesday:", and similarly for day equal to 3, it prints "Wednesday:".
- Inside each of these cases, we use another switch statement (a nested switch) to evaluate the value of time for that particular day. This inner switch statement has cases for "morning", "afternoon", and "evening".
- If time equals "morning", the corresponding message like "Good Morning, Monday!" is printed. If time equals "afternoon", it prints "Good Afternoon, Monday!", and if time equals "evening", it prints "Good Evening, Monday!". If time doesn't match any of these values, the default case is executed, and it prints "Hello, Monday!".
- This nested structure is repeated for the cases of day equal to 2 (Tuesday) and 3 (Wednesday). Depending on the value of time, the appropriate greeting is printed.
- If day doesn't match any of the defined cases (i.e., it's not 1, 2, or 3), the outer default case is executed, and the program prints "Invalid Day", indicating that the input is not valid.
- The break statements ensure that once the greeting for the specific day and time is printed, the program exits the corresponding switch block and continues with the rest of the program.
Java Enum In Switch Statement
In Java, enums (short for "enumerations") are a special data type that represents a group of constants. Starting from Java 5, enums can be used in switch statements, allowing you to perform actions based on the specific constant of an enum. This makes the code more readable and efficient, especially when dealing with a fixed set of related constants.
How It Works:
- An enum defines a set of constants (values).
- In a switch statement, you can compare the enum values just like regular constants.
- Each case corresponds to one of the enum constants, and based on the value, the appropriate block of code is executed.
- The default case can be used for any unmatched values, although all enum values should typically be handled in the switch.
Code Example:
Output (set code file name as EnumSwitchExample.java):
Midweek!
Explanation:
In the above code example-
- First, we define an enum called Day. Enums are a special type in Java that represent a fixed set of constants. Here, we define seven constants for the days of the week: MONDAY, TUESDAY, WEDNESDAY, THURSDAY, FRIDAY, SATURDAY, and SUNDAY.
- In the main() method, we declare a variable day of type Day and assign it the value Day.WEDNESDAY. This means the program will initially consider Wednesday, but we can change this to any other day to test different outputs.
- The switch statement evaluates the value of the day variable. It checks which of the enum constants (MONDAY, TUESDAY, etc.) matches the value of day.
- For the case where day is MONDAY, the program prints "Start of the week!" and exits the switch block using the break statement.
- Similarly, for each of the other days (from TUESDAY to SUNDAY), the program prints a corresponding message like "Second day of the week!" for Tuesday, "Midweek!" for Wednesday, and so on.
- If the value of day doesn't match any of the defined enum constants (though this won't happen in this case), the default case would be executed, printing "Invalid day!".
- The break statements are used to terminate each case once the appropriate message is printed, ensuring the program doesn’t fall through to the next case.
Sharpen your coding skills with Unstop's 100-Day Coding Sprint and compete now for a top spot on the leaderboard!
Java Wrapper Classes In Switch Statements
In Java, wrapper classes are used to wrap primitive types into objects. Examples include Integer for int, Character for char, and Double for double. While primitive types can be used in a switch statement, wrapper classes can also be used in certain situations to allow the use of objects in a switch.
However, there is a restriction when using wrapper classes in switch statements: only objects that can be unboxed to primitive values (like Integer, Character, Byte) can be used in switch statements. As of Java 7, you can use Integer, Character, Byte, and Short in switch statements, but not Long, Double, or Boolean.
How It Works:
- When you use a wrapper class in a switch statement, it is auto-unboxed to the corresponding primitive type.
- The wrapper class objects are then compared against the case values.
- The switch will execute the matching case for the value inside the wrapper object.
Code Example:
Output (set code file name as WrapperSwitchExample.java):
Number is three
Explanation:
In the above code example-
- We start by declaring a variable number of type Integer, which is the wrapper class for the primitive type int. This variable is assigned the value 3. The wrapper class allows us to use object-like behavior for primitive types.
- The switch statement is then used to evaluate the value of number. It checks the value against the defined case options.
- If number equals 1, the program matches the case 1 block, prints "Number is one," and exits the switch block using the break statement.
- Similarly, if number equals 2, the case 2 block is executed, printing "Number is two," followed by a break.
- For number equal to 3, the case 3 block is executed. In this case, the program prints "Number is three," and then exits the switch block.
- If number equals 4, the case 4 block runs, and the program prints "Number is four," followed by exiting the switch.
- If the value of number doesn’t match any of the defined cases, the default block is executed. This block prints "Invalid number" to indicate that the value doesn’t match any of the specified cases.
- The break statements after each case ensure that once the matching case is executed, the program doesn’t fall through to the next case.
Uses Of Switch Statement In Java
The switch statement in Java provides a clean and efficient way to execute code based on specific values of an expression. It is particularly useful in scenarios where multiple conditions need to be checked. Below are some common uses of the switch statement in Java:
1. Simplifies Multiple Conditional Checks
When a variable needs to be compared with many constant values, switch offers a more readable alternative to using multiple if-else conditions. Example: Checking a number to determine if it matches specific cases (e.g., 1, 2, 3).
2. Improves Readability
Using a switch statement makes the code more structured and easier to understand compared to a series of nested if-else blocks.
3. Handling Fixed Choices or States
Ideal for scenarios where a variable can have a predefined set of values (like enums, days of the week, menu options, etc.). Example: Selecting menu options in a console application.
4. Efficient for Fixed Number of Cases
The switch statement is more efficient than if-else for a fixed number of comparisons, as it often uses lookup tables or jump tables under the hood for faster execution.
5. Works with Various Data Types
Supports int, char, byte, short, String, and enum types. Example: String-based switch for commands like "start", "stop", "pause".
6. Supports Nested and Complex Conditions
Allows nested switch statements to handle multi-level conditions. Example: Classifying both days of the week and time of day.
7. Error Handling or Validation
Can be used to validate user inputs or handle errors by matching specific cases. Example: Handling invalid inputs with a default case.
8. Reduces Boilerplate Code
Combines multiple cases with the same output using a fall-through mechanism. Example: Grouping cases like weekends (case SATURDAY, case SUNDAY) to execute the same code.
9. State Machine Implementation
Often used in implementing simple state machines where different states (or cases) require different actions. Example: Traffic light states (RED, YELLOW, GREEN).
10. Menu-Driven Programs
Commonly used in applications where the user selects from a menu of options. Example: A program offering operations like addition, subtraction, multiplication, and division.
Are you looking for someone to answer all your programming-related queries? Let's find the perfect mentor here.
Conclusion
The switch statement in Java is a powerful control structure that simplifies the decision-making process in programs. By providing a clean and efficient way to handle multiple conditions, it eliminates the complexity of using multiple if-else blocks. With support for various data types, including int, String, enum, and wrapper classes, the switch statement is versatile and well-suited for a wide range of applications.
Whether you're building menu-driven programs, handling fixed choices, or implementing state machines, the switch statement enhances code readability and maintainability. Its ability to group cases and handle defaults ensures that your programs remain robust and error-free. By mastering the use of switch, developers can write cleaner, more efficient, and more elegant code.
Frequently Asked Questions
Q. What is a switch statement in Java?
The switch statement in Java is a control structure that evaluates a single expression and matches its value to one of several predefined case labels. It executes the code associated with the matched case, making it ideal for handling fixed values or conditions.
Q. Why is the switch statement considered more efficient than if-else for certain conditions?
The switch statement is considered more efficient than if-else in certain scenarios because of how it is implemented internally and how it handles comparisons:
- Direct Jump Using Lookup Tables: The switch statement often uses lookup tables or jump tables internally. These tables map the case values directly to memory locations, allowing the program to "jump" directly to the correct case block. This eliminates the need for sequential evaluations.
- Constant-Time Evaluation: In many cases, especially when there are a large number of cases, the switch statement achieves constant-time performance for value matching, whereas if-else checks conditions sequentially. As the number of conditions grows, the if-else structure becomes slower due to linear evaluation.
- Readability and Maintainability: While not strictly related to efficiency, a switch statement is more concise and readable than multiple nested if-else blocks, reducing the chance of errors and making it easier to maintain.
When is it most efficient?
- When the number of conditions is large.
- When the conditions are based on constant values or discrete options (e.g., enum, String, or integers).
Q. Which data types are supported in a switch statement in Java?
The switch statement in Java supports the following data types:
- Primitive types: int, char, byte, and short.
- Wrapper classes: Integer, Character, Byte, and Short (introduced in Java 7).
- Enums: Enumerations can be directly used in switch statements.
- Strings: Strings became supported in Java 7.
Other types like long, float, double, and boolean are not supported.
Q. What happens if there is no break statement in a switch case?
The break statement in a switch ensures that the control exits the switch block after a case is executed. If there is no break statement after a case block, the control falls through to the subsequent case(s), executing their code until a break is encountered or the switch ends. This behavior can be useful when multiple cases need to execute the same block of code, but it may also lead to unintended results if not handled properly. For Example-
int day = 2;
switch (day) {
case 1:
System.out.println("Monday");
case 2:
System.out.println("Tuesday");
case 3:
System.out.println("Wednesday");
break;
}
Q. Is the default case mandatory in a switch statement?
No, the default case is not mandatory in a switch statement. However, it is a best practice to include it to handle unexpected or unmatched values. If no case matches the expression, and no default case is provided, the switch statement will do nothing. For Example-
int number = 5;
switch (number) {
case 1:
System.out.println("One");
break;
case 2:
System.out.println("Two");
break;
// No default case
}
Q. Can a switch statement handle null values for Strings or Wrapper classes?
No, a switch statement in Java cannot handle null values for Strings or Wrapper classes. If the expression evaluated in the switch is null, it will throw a NullPointerException at runtime. This is because the switch statement attempts to dereference the value to match it against the case labels. To avoid this issue, you should ensure that the expression being passed to the switch is not null by using a null check beforehand. For instance, you can use an if-else block to handle null cases or assign a default non-null value to the variable before the switch.
Q. Can the switch statement be used for complex expressions or ranges?
No, the switch statement in Java cannot directly handle complex expressions, conditions, or ranges. It only supports constant values or expressions that evaluate to a single constant. For ranges or complex logic, you need to use if-else or workarounds like:
- Using multiple cases with fall-through for ranges (e.g., case 1: case 2: case 3: for a range 1-3).
- Handling the logic outside the switch and passing a simplified variable to the switch.
With this, we come to an end to our discussion on the switch statement in Java. Here are a few other topics that you might be interested in reading:
- Convert String To Date In Java | 3 Different Ways With Examples
- Final, Finally & Finalize In Java | 15+ Differences With Examples
- Super Keyword In Java | Definition, Applications & More (+Examples)
- How To Find LCM Of Two Numbers In Java? Simplified With Examples
- How To Find GCD Of Two Numbers In Java? All Methods With Examples
- Volatile Keyword In Java | Syntax, Working, Uses & More (+Examples)