Java Switch Expressions

In Java 12 and Java 13, Switch Expressions were added as preview features, and in Java 14 they became a standard feature. The Switch Expressions feature extends regular Java switch statements and can be used as either a statement or an expression. The entire switch block evaluates to a value that can then be assigned to a variable.

Switch Statement VS Switch Expressions

The traditional switch statement in Java has a number of limitations that can make it difficult to use in certain situations. One of the main limitations is that it can only be used with primitive types (byte, short, int, long) and their corresponding wrapper classes (Byte, Short, Integer, Long), as well as the char type. This means that it cannot be used with other types, such as strings or enums, without converting them to a compatible type first.

Another limitation of the traditional switch statement is that it requires each case to end with a break statement in order to avoid fall-through. This can be tedious to write and can lead to errors if a break statement is accidentally omitted. Additionally, it is not possible to return a value from a traditional switch statement.

Switch expressions were introduced in Java 12 as a preview feature to address these limitations of the traditional switch statement. With switch expressions, it is now possible to use the switch statement with other types, such as strings and enums, without the need to convert them to a compatible type first. In addition, switch expressions allow for the use of the yield keyword, which allows a value to be returned from the expression.

Switch expressions also allow for a more concise syntax that eliminates the need for break statements. Instead, each case can be treated as an expression that returns a value. This makes switch expressions easier to read and less error-prone.

Overall, switch expressions are a powerful addition to the Java language that address many of the limitations of the traditional switch statement and provide a more flexible and concise syntax for conditional branching.

Examples of switch Statement in Java

Regular Java switch statement

class Test {
    public static void main(String[] args) {
        String color = "blue";
        switch (color) {
            case "white":
                System.out.println("The color is white.");
                break;
            case "yellow":
                System.out.println("The color is yellow.");
                break;
            case "blue":
                System.out.println("The color is blue.");
                break;
            case "green":
                System.out.println("The color is green.");
                break;
            default:
                System.out.println("Unrecognized color!");
        }
    }
}
Output: 
The color is blue.
Now, this can be written like this:
class Test {
    public static void main(String[] args) {
        String color = "blue";
        switch (color) {
            case "white" -> System.out.println("The color is white.");
            case "yellow" -> System.out.println("The color is yellow.");
            case "blue" -> System.out.println("The color is blue.");
            case "green" -> System.out.println("The color is green.");
            default -> System.out.println("Unrecognized color!");
        }
    }
}
Output
The color is blue.
As you can see, the new -> arrow sign has been introduced, and we no longer need to use break.

Switch Expressions with multiple statements

class Test {
    public static void main(String[] args) {
        String day = "Tuesday";
        switch (day) {
            case "Monday", "Tuesday", "Wednesday", "Thursday", "Friday" -> System.out.println("It is a week day.");
            case "Saturday", "Sunday" -> System.out.println("It is a weekend.");
        }
    }
}
Output: 
It is a week day.
We can also assign a switch expression to a variable:
class Test { 
    public static void main(String[] args) { 
        String day = "Tuesday"; 
        String result = switch (day) { 
            case "Monday", "Tuesday", "Wednesday", "Thursday", "Friday" -> "Weekday"; 
            case "Saturday", "Sunday" -> "Weekend"; 
            default -> throw new IllegalStateException("Unexpected value: " + day); 
        }; 
        System.out.println(result); 
    } 
}
Output: 
Weekday
The value after the -> sign will be returned. We can also replace the -> sign with a colon (:) but in this case, if we want to return a value, we need to use the newly introduced keyword yield.

yield Keyword Example in Java

class Test {

  public static void main(String[] args) {
    System.out.println(isNumberLessThenFive(4));
    System.out.println(isNumberLessThenFive(8));
  }

  static boolean isNumberLessThenFive(int number) {
    return switch (number) {
      case 1, 2, 3, 4:
        yield true;
      case 5, 6, 7, 8, 9, 10:
        yield false;
      default:
        throw new IllegalStateException("Unexpected value: " + number);
    };
  }
}

Output:

true 
false

Some key points

Some key points to note about switch expressions in Java are:

  • We don’t need to use the break statement anymore.
  • If we use the -> arrow sign, we can skip the yield keyword.
  • If we use : instead of ->, we need to use the yield keyword if the switch case needs to return some value.
  • If we have multiple statements inside one switch case block, we need to put them inside curly braces {}.

Examples of more complex use cases for switch expressions

Switch expressions in Java can be used for more than just simple integer or string comparisons. Here are some more complex use cases:

Pattern matching

Object obj = new String("Hello");

String result = switch (obj) {
    case Integer i -> "An integer: " + i;
    case String s && s.length() > 3 -> "A string with length greater than 3: " + s;
    case String s -> "A string: " + s;
    case SomeClass c && c.someMethod() -> "An instance of SomeClass that returns true from someMethod(): " + c;
    case SomeClass c -> "An instance of SomeClass: " + c;
    default -> "Something else";
};

In this example, we use the case keyword to match on the type and value of the obj variable. We can also use additional conditions with the && operator to further refine the matching criteria.

Lambda expressions

Switch expressions can also be used as a replacement for lambda expressions. Consider the following example:

Function<Integer, String> func = switch (input) {
    case 1 -> (i) -> "One";
    case 2 -> (i) -> "Two";
    case 3 -> (i) -> "Three";
    default -> throw new IllegalArgumentException("Unexpected value: " + input);
};

String result = func.apply(input);

In this example, we use the switch expression to create a Function object that takes an integer input and returns a string. Each case of the switch expression returns a lambda expression that performs a specific transformation on the input. We can then use the resulting Function object to apply the transformation to a given input.

These are just a few examples of the more complex use cases for switch expressions in Java. With their flexibility and power, switch expressions are a valuable tool for writing concise and expressive code.

Performance Considerations

When using switch expressions, it’s important to consider their performance compared to other conditional statements like if-else statements and ternary operators. In general, switch expressions can be faster than if-else statements when comparing a large number of values, because the Java compiler can generate more efficient bytecode for switch statements. However, this can depend on the specific use case and the number of cases being compared.

It’s also important to note that switch expressions can only be used with integer types (including char and enums) in Java 12 and 13, but this restriction was lifted in Java 14 and later versions. This means that if you need to compare non-integer values, you may need to use if-else statements or another type of conditional statement.

Another consideration is that switch expressions can be less readable than if-else statements in some cases, especially when dealing with complex expressions or multiple conditions. It’s important to balance the readability of the code with its performance characteristics when deciding whether to use switch expressions or another type of conditional statement.

In general, it’s a good idea to benchmark your code and compare the performance of different conditional statements to find the best solution for your specific use case. Keep in mind that micro-optimizations like this should only be considered after your code is already working correctly and any larger optimizations have been implemented.

Conclusion

In conclusion, switch expressions are a powerful addition to the Java programming language, providing more concise and readable code for conditional statements. They offer several advantages over traditional switch statements, including the ability to use them as expressions and improved syntax for multi-case scenarios. In addition, switch expressions can be used for more complex use cases such as pattern matching and lambda expressions.

However, it’s important to consider the performance of switch expressions compared to other conditional statements like if-else statements and ternary operators, especially in cases where a large number of values are being compared. It’s also important to balance the readability of the code with its performance characteristics when deciding whether to use switch expressions or another type of conditional statement.

By understanding the syntax and best practices for using switch expressions in Java, you can write more efficient and readable code for your Java applications.

Leave a Reply

Your email address will not be published. Required fields are marked *