0% found this document useful (0 votes)
14 views8 pages

Pattern Matcing For Switch

Uploaded by

Sourabh Jain
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
14 views8 pages

Pattern Matcing For Switch

Uploaded by

Sourabh Jain
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 8

Pattern Matching for switch in Java

Pattern Matching for switch is a feature introduced in Java 17 (as a preview) and enhanced in later
versions, including Java 21. It allows for more flexible and expressive control flow by integrating
pattern matching directly into the switch statement. This feature simplifies handling different types
or patterns within a single switch construct, making the code more concise and readable.

Key Concepts of Pattern Matching for switch

1. Pattern Matching: This enables you to specify the shape or type of an object and perform
operations based on that shape.

2. Type Patterns: In switch statements, you can match the type of an object and bind it to a
variable in one step.

3. Exhaustive Checking: The compiler ensures all possible cases are covered, leading to safer
code.

4. Null Safety: switch can handle null values explicitly, avoiding potential NullPointerExceptions.

Benefits of Pattern Matching for switch

1. Simplifies Control Flow: Reduces the need for manual instanceof checks and type casting,
streamlining code that needs to handle multiple types or patterns.

2. Cleaner Code: Combining type checks and casts into a single operation makes the code more
concise.

3. Better Readability: Pattern matching makes complex branching logic easier to follow by
keeping everything within the switch statement.

Here we don’t need to put break


Previously we are using it like this: (in below if we don’t use the break statement this will not give
us the desired output But now it is giving )

public class SwitchPattern {


public static void main(String[] args) {

String day="Monday";

switch(day){
case "Saturday","Sunday":
System.out.println("6am");
break;
case "Monday":
System.out.println("8am");
break;
default:
System.out.println("7am");

}
}
}
now we can implement the Switch case like this: (we are using -> so we do not have to use the break
statement.)

public class SwitchPattern1 {


public static void main(String[] args) {

String day="Monday";

switch(day){
case "Saturday","Sunday"-> System.out.println("6am");

case "Monday"-> System.out.println("8am");

default-> System.out.println("7am");

}
}
}
We can also use a variable here like this i.e (result ):

public class SwitchPattern2 {


public static void main(String[] args) {

String day="Monday";
String result = "";

switch(day){
case "Saturday","Sunday" -> result="6am";

case "Monday" -> result="8am";

default -> result="7am";

}
System.out.println(result);
}
}
We can also remove the result from multiple line like this:

public class SwitchPattern3 {


public static void main(String[] args) {

String day="Monday";
String result = "";

result = switch(day)
{
case "Saturday","Sunday" -> "6am";

case "Monday" -> "8am";

default -> "7am";

};
System.out.println(result);
}
}
If we want to used the yield instead of (arrow ->) that we can do like this :

public class SwitchPattern {


public static void main(String[] args) {

String day="Monday";
String result = "";

result = switch(day)
{
case "Saturday","Sunday" : yield "6am";

case "Monday" : yield "8am";

default : yield"7am";

};
System.out.println(result);
}
}
Another Example:

Applying Pattern Matching in switch Statements

Let’s take a look at how pattern matching simplifies switch statements with an example.

Example 1: Basic Type Matching with switch

public class PatternMatchingSwitchExample {


public static void main(String[] args) {
Object obj = "Hello, world!";
printObjectInfo(obj);
}

public static void printObjectInfo(Object obj) {


switch (obj) {
case Integer i -> System.out.println("The integer value is " + i);
case String s -> System.out.println("The string length is " + s.length());
case Double d -> System.out.println("The double value is " + d);
case null -> System.out.println("The object is null");
default -> System.out.println("Unknown type");
}
}
}

Explanation:

 Type Matching: In the switch, we check for types like Integer, String, and Double. If the
object matches a type, it's automatically cast, and we can use the variable (i, s, or d) in that
block.

 Null Handling: A specific case for null can be added, ensuring null-safe operations.

 Cleaner Code: We no longer need instanceof checks and explicit casting; the pattern
matching handles both.
Example 2: Enhanced Matching with Complex Types

public class PatternMatchingSwitchExample2 {

public static void main(String[] args) {

Object obj = 45.67;

printDetailedInfo(obj);

public static void printDetailedInfo(Object obj) {

switch (obj) {

case Integer i when i > 50 -> System.out.println("Large integer: " + i);

case Integer i -> System.out.println("Integer: " + i);

case String s -> System.out.println("String with length " + s.length());

case Double d when d > 40.0 -> System.out.println("Large double: " + d);

case Double d -> System.out.println("Double: " + d);

default -> System.out.println("Unknown object");

Explanation:

 Guarded Patterns (when clause): We can add conditional logic to refine the pattern. For
instance, case Integer i when i > 50 matches only integers greater than 50.

 Multiple Pattern Matches: The switch can handle both types and conditions within the same
construct, allowing fine-tuned control flow.

You might also like