Java - Switch Expressions

Hello there, future Java programmers! Today, we're going to dive into one of the most exciting features introduced in Java 12 and enhanced in Java 14: Switch Expressions. As your friendly neighborhood computer science teacher, I'm here to guide you through this journey, even if you've never written a single line of code before. So, buckle up and let's get started!

Java - Switch Expressions

What are Switch Expressions?

Before we jump into switch expressions, let's take a quick detour to understand what a switch statement is. Imagine you're at an ice cream parlor, and depending on your flavor choice, you get a different topping. That's essentially what a switch statement does in programming – it allows you to execute different code based on different conditions.

Now, switch expressions take this concept and make it even more powerful and concise. They allow us to treat the entire switch block as an expression that can return a value. It's like upgrading from a regular ice cream cone to a deluxe sundae!

The Old Way: Traditional Switch Statements

Let's start with a traditional switch statement to see how we used to do things:

String day = "MONDAY";
String typeOfDay;

switch (day) {
    case "MONDAY":
    case "TUESDAY":
    case "WEDNESDAY":
    case "THURSDAY":
    case "FRIDAY":
        typeOfDay = "Weekday";
        break;
    case "SATURDAY":
    case "SUNDAY":
        typeOfDay = "Weekend";
        break;
    default:
        typeOfDay = "Invalid day";
}

System.out.println(typeOfDay);

In this example, we're determining whether a day is a weekday or weekend. Notice how we need to use break statements to prevent fall-through, and we have to declare typeOfDay outside the switch block.

The New Way: Switch Expressions

Now, let's see how we can achieve the same result using switch expressions:

String day = "MONDAY";
String typeOfDay = switch (day) {
    case "MONDAY", "TUESDAY", "WEDNESDAY", "THURSDAY", "FRIDAY" -> "Weekday";
    case "SATURDAY", "SUNDAY" -> "Weekend";
    default -> "Invalid day";
};

System.out.println(typeOfDay);

Wow! Look at how much cleaner and more concise that is. We've combined multiple cases, removed the break statements, and assigned the result directly to typeOfDay. It's like cleaning up your room – suddenly everything is neat and tidy!

Switch Expression Using "case L ->" Labels

The arrow syntax (->) is a key feature of switch expressions. It allows us to provide a concise way to specify both the case label and its associated action. Let's look at another example:

int dayNumber = 3;
String dayName = switch (dayNumber) {
    case 1 -> "Monday";
    case 2 -> "Tuesday";
    case 3 -> "Wednesday";
    case 4 -> "Thursday";
    case 5 -> "Friday";
    case 6 -> "Saturday";
    case 7 -> "Sunday";
    default -> "Invalid day number";
};

System.out.println("Day " + dayNumber + " is " + dayName);

In this example, we're converting a day number to its corresponding name. The arrow syntax makes each case a single, easy-to-read line. It's like a signpost pointing directly to the right answer!

Switch Expression Using "case L:" Statements and the yield Statement

Sometimes, you might need to do more than just return a simple value in your switch expression. That's where the yield statement comes in handy. It's like saying, "I'm done with my calculations, here's the final answer!"

Let's look at an example:

int month = 8;
String season = switch (month) {
    case 12, 1, 2: 
        yield "Winter";
    case 3, 4, 5: 
        yield "Spring";
    case 6, 7, 8: 
        yield "Summer";
    case 9, 10, 11: 
        yield "Fall";
    default: {
        String message = "Invalid month: " + month;
        System.out.println(message);
        yield "Unknown";
    }
};

System.out.println("The season for month " + month + " is " + season);

In this example, we're determining the season based on the month. Notice how we use yield to return values, especially in the default case where we're doing a bit more processing.

Advanced Usage: Expressions in Case Labels

One of the coolest features of switch expressions is that you can use expressions in case labels. It's like giving your switch statement a superpower! Here's an example:

record Person(String name, int age) {}

Person person = new Person("Alice", 25);

String lifeStage = switch (person) {
    case Person p when p.age() < 13 -> "Child";
    case Person p when p.age() >= 13 && p.age() < 20 -> "Teenager";
    case Person p when p.age() >= 20 && p.age() < 60 -> "Adult";
    case Person p when p.age() >= 60 -> "Senior";
    default -> "Unknown";
};

System.out.println(person.name() + " is a " + lifeStage);

In this example, we're using a record (another cool Java feature) to represent a person, and then using switch expressions with complex conditions to determine their life stage. It's like having a personal life coach in your code!

Conclusion

Switch expressions are a powerful tool in Java that can make your code more readable, concise, and less error-prone. They're like upgrading from a flip phone to a smartphone – suddenly, you can do so much more with less effort!

Remember, programming is all about practice. So, don't be afraid to experiment with these concepts. Try creating your own switch expressions, play around with different scenarios, and most importantly, have fun with it!

As we wrap up, here's a table summarizing the key methods we've discussed:

Method Description
-> Arrow syntax for concise case labels and actions
yield Statement to return a value from a switch expression
case L when condition Pattern matching in case labels

Happy coding, and may your switches always express themselves clearly!

Credits: Image by storyset