Pattern Matching for Switch in Java 21

RMAG news

Pattern matching has been a highly anticipated feature in Java, bringing more power and flexibility to the language. Java 21 introduces pattern matching for switch statements, which simplifies the code and reduces boilerplate. Let’s explore how this new feature works and why it’s beneficial.

What is Pattern Matching for Switch?

Pattern matching for switch allows you to match a value against patterns, making the code more expressive and readable. Instead of using multiple if-else statements or complex switch cases, you can now write more concise and maintainable code.

Benefits of Pattern Matching for Switch

Readability: Makes the code easier to read and understand.

Conciseness: Reduces the amount of boilerplate code.

Type Safety: Provides better type checking at compile time.

How to Use Pattern Matching for Switch

Here’s a simple example to illustrate how pattern matching for switch works:

static String formatterPatternSwitch(Object obj) {
return switch (obj) {
case Integer i -> String.format(“int %d”, i);
case Long l -> String.format(“long %d”, l);
case Double d -> String.format(“double %f”, d);
case String s -> String.format(“String %s”, s);
default -> obj.toString();
};
}

In this example, formatterPatternSwitch takes an Object and returns a formatted string based on its type. Here’s a breakdown of what’s happening:

Switch Expression: The switch expression takes the obj and matches it against different patterns.
Case Patterns: Each case specifies a pattern to match:

Integer i: Matches if obj is an instance of Integer and binds the value to i.
Long l: Matches if obj is an instance of Long and binds the value to l.
Double d: Matches if obj is an instance of Double and binds the value to d.
String s: Matches if obj is an instance of String and binds the value to s.

Default Case: The default case handles any values that do not match the specified patterns, converting them to a string using obj.toString().

Let’s me give with detailed example case: Handling Different Shapes

Consider a scenario where you need to handle different shapes and calculate their areas. Here’s how pattern matching for switch can simplify the code:

abstract sealed class Shape permits Circle, Square, Rectangle {}

final class Circle extends Shape {
double radius;
Circle(double radius) { this.radius = radius; }
}

final class Square extends Shape {
double side;
Square(double side) { this.side = side; }
}

final class Rectangle extends Shape {
double length, width;
Rectangle(double length, double width) { this.length = length; this.width = width; }
}

static double calculateArea(Shape shape) {
return switch (shape) {
case Circle c -> Math.PI * c.radius * c.radius;
case Square s -> s.side * s.side;
case Rectangle r -> r.length * r.width;
};
}

In this example:

Sealed Classes: Shape is a sealed class, and only Circle, Square, and Rectangle can extend it.
Switch Expression: The calculateArea method uses a switch expression to determaine the type of shape and calculate its area.
Case Patterns: Each case matches a spesific shape type and performs the corressponding area calculation:

Circle c: Matches if shape is a Circle and binds it to c, the calculates the area using c.radius

Square s: Matches if shape is a Square and binds it to s, the calculates the area using s.side

Rectangle r: Matches if shape is a Rectangle and binds it to r, the calculates the area using r.length and r.width.

Conclusion

Pattern matching for switch in Java 21 is a powerful feature that enhances code readability, conciseness, and type safety. By allowing you to match values against patterns directly in switch statements, it simplifies many common coding tasks. Java developers should definitely explore and adopt this feature to write cleaner and more maintainable code.

Feel free to modify or expand upon this section to suit your needs!

Please follow and like us:
Pin Share