Javatpoint Logo
Javatpoint Logo

Pattern Matching for Switch

The pattern matching regarding the switch statements was introduced in the Java 12 version and later introduced as a standard feature in the Java 13 version. Let's understand about pattern matching for switch in Java in detail in the following paragraphs.

The main purpose of it was to make the readability of the code simpler and introduce a simple and expressive technique for performing pattern matching check between the statements of switch keyword in Java.

Pattern Matching for Switch in Java

Previously in Java, the statements of switch keyword were held withing simple equality checks using either constants or primitive data types. In Java, the switch statement gains lot of flexibility by introducing the pattern matching as it allows users and developers for using pattern for matching complex objects and data structures.

One of the major benefits of using pattern matching for switch keyword in Java is that it provides the ability for removing the boilerplate code. In situations where several if-else statements or nested instanceOf statements are followed by explicit type of casting, the users or developers can create simple and understandable. With the usage of pattern matching for switch in Java, the code becomes more streamlined and least prone to errors.

Syntax for Pattern Matching in Switch Statements

The syntax utilized for pattern matching in switch statements in Java consists the utilization of the case keyword which must be followed by a pattern. The patterns mentioned previously may contain several types of elements, such as patterns of type which checks the object's type.

Let's understand about the pattern matching in switch statements in Java with the help of an example program.

Example 1:

It is a traditional syntax or approach of using switch statement in Java and it includes the usage of keywords switch, case, default, and break.

Filename: PatternMatchingSwitch.java

Output:

The number is Two

Example 2:

It is a lambda syntax or approach of using switch statement.

Filename: PatterMatching1.java

Output:

Today is Friday

Let's understand in detail about pattern matching in switch keyword in Java by taking an example of matching on strings.

Example 3:

This is a traditional syntax or approach of using switch keyword in Java.

Filename: PatterMatching2.java

Output:

The fruit is a banana.

Let's look at another example that works on matching on constants of Enum in Java.

Filename: PatternMatching3.java

Output:

The Color is red.

This is all the required explanation and examples related to pattern matching for switch keyword in Java.







Youtube For Videos Join Our Youtube Channel: Join Now

Feedback


Help Others, Please Share

facebook twitter pinterest

Learn Latest Tutorials


Preparation


Trending Technologies


B.Tech / MCA