Java Switch Expressions Example

1. Introduction

In this blog post, we'll delve into the world of Java Switch Expressions. Introduced in Java 12 as a preview feature and later finalized in Java 14, Switch Expressions extend the traditional switch statement, making it more flexible and functional.

Definition

Switch Expressions are an enhancement of the traditional switch statement in Java. They allow for multiple values to be returned from a switch statement, using a more concise and expressive syntax. This feature aligns Java with a more functional programming approach.

2. Program Steps

1. Define a scenario for using a switch expression.

2. Write a method that includes a switch expression.

3. Demonstrate the method with different inputs to see how the switch expression works.

3. Code Program

public class SwitchExpressionsExample {
    // Method using a switch expression
    public static String getDayType(String day) {
        return switch (day) {
            case "MONDAY", "TUESDAY", "WEDNESDAY", "THURSDAY", "FRIDAY" -> "Weekday";
            case "SATURDAY", "SUNDAY" -> "Weekend";
            default -> "Invalid day";
        };
    }

    public static void main(String[] args) {
        System.out.println("Tuesday is a " + getDayType("TUESDAY"));
        System.out.println("Saturday is a " + getDayType("SATURDAY"));
        System.out.println("Random day is a " + getDayType("RANDOMDAY"));
    }
}

Output:

Tuesday is a Weekday
Saturday is a Weekend
Random day is a Invalid day

Explanation:

1. The getDayType method uses a switch expression to return different strings based on the input day.

2. The switch expression covers cases for weekdays and weekends, each returning a corresponding string.

3. The default case in the switch expression handles any input that doesn't match the specified days.

4. In the main method, getDayType is called with different arguments to demonstrate how the switch expression handles various cases.

5. The output shows how the switch expression simplifies decision-making logic, making the code more readable and concise.


Comments