Switch statements versus switch expressions in Java
Introduction:
Switch statements and switch expressions are essential control flow statements in Java that allow developers to choose between different alternative actions, depending on a given input variable. In this article, we will take an in-depth look at the switch statement and switch expression, and their differences.
1. The Switch Construct:
The switch construct is a multi-way branch statement that transfers control to a specific code block within the switch, based on a given input variable. There are two types of switch constructs in Java – the switch statement and the switch expression, each of which can be written using the colon (:) notation or the arrow (->) notation.
2. The Switch Statement:
The switch statement is used to perform different actions based on a given input value. Its syntax is as follows:
switch (selector_expression) {
case value1: // code block
case value2: // code block
...
case valueN: // code block
default: // code block
}
Some key points to note about the switch statement: The `selector_expression
` must be an expression that returns a value of a primitive data type (char, byte, short, or int), a wrapper class (Character, Byte, Short, or Integer), an Enum type, or a String.
The `case
` constants must be type-compatible with the `selector_expression
`.
The statements within each `case
` can be a single statement, a group of statements, or a block statement.
The `default
` block will be executed if none of the given `case
` constants match the input value.
The `case
` constants can appear in any order within the switch block.
When multiple `case
` labels have a common action, they can be grouped together.
The `case
` labels must end with a `break` statement to avoid fall-through to the next `case
` label.
Starting from Java 7, the `switch` statement can also be used with Strings.
Example of Switch Statement with the Colon Notation:
int value = 5;
switch (value) {
case 1:
System.out.println("Value is 1");
break;
case 2:
System.out.println("Value is 2");
break;
case 5:
System.out.println("Value is 5");
break;
default:
System.out.println("Value doesn't match any of the constants");
}
3. The Switch Expression:
A switch expression has the same functionality as a switch statement, but it returns a value. There are two forms of the switch expression – the colon (`:`) notation and the arrow (`->`) notation.
3.1. The Yield Statement:
In switch expressions, the `yield` statement is used to return a value from the expression. It must be the last statement in each `case` block. Here's an example of a switch expression using the colon notation:
String day = "MONDAY";
int numLetters = switch (day) {
case "MONDAY", "FRIDAY", "SUNDAY" -> 6;
case "TUESDAY" -> 7;
case "THURSDAY", "SATURDAY" -> 8;
case "WEDNESDAY" -> 9;
default -> throw new IllegalStateException("Unexpected value: " + day);
};
System.out.println("Number of letters in the day name: " + numLetters);
3.2. The Switch Expression with the Arrow Notation:
In Java 14, a simplified version of the switch expression was introduced using the arrow (`->`) notation. In this form, the `yield` statement is not needed, and the `break` statement is not allowed. Here's an example:
String day = "MONDAY";
int numLetters = switch (day) {
case "MONDAY", "FRIDAY", "SUNDAY" -> 6;
case "TUESDAY" -> 7;
case "THURSDAY", "SATURDAY" -> 8;
case "WEDNESDAY" -> 9;
default -> throw new IllegalStateException("Unexpected value: " + day);
};
System.out.println("Number of letters in the day name: " + numLetters);
4. Differences Between the Switch Statement and Switch Expression:
There are several differences between the two switch constructs, which are summarized below:
Expression Result: The switch statement does not return a value, while the switch expression returns a value.
Syntax: The switch statement uses the colon (`:`) notation, while the switch expression uses the arrow (`->`) notation.
`break` Statement: The `break` statement is required in each `case` block in the switch statement, while it is optional in the switch expression.
`default` Block: The `default` block is required in the switch statement, while it is optional in the switch expression.
Fall-Through: Fall-through is not allowed in the switch expression, while it is allowed in the switch statement.
Multiple Constants: Multiple `case` constants can be in a single `case` label in the switch statement, while the switch expression does not allow this.
Data Types: The switch statement allows primitive data types, wrapper classes, Enums, and Strings as `selector_expression`, while the switch expression only supports Enums and Strings.
Java Version: The switch statement has been available since the early versions of Java, while the switch expression was introduced in Java 12.
Scope: The variables defined in each `case` block in the switch expression are scoped to that block only, while they are accessible in the entire `switch` statement in the switch statement.
Conclusion:
Switch statements and switch expressions are powerful control flow statements in Java that allow developers to handle multiple conditions efficiently. While the switch statement has been available since the early versions of Java, the switch expression was introduced in the recent Java versions and offers more concise syntax and better handling of data types. Choosing between the two will depend on your project requirements and the Java version you are using.
Note: The recently added Java Certifications, such as Java 21 Developer and Java 17 Developer, now require proficiency in switch pattern matching.
Author | JEE Ganesh | |
Published | 2 months ago | |
Category: | Java Programming | |
HashTags | #Java #Programming #JavaCertification |