Open In App

Pattern Matching for Switch in Java

Last Updated : 08 Apr, 2023
Improve
Improve
Like Article
Like
Save
Share
Report

Pattern matching for a switch in Java is a powerful feature that was introduced in Java 14. Before this update, a switch expression could only be used to match the type of a value, rather than its actual value. However, by comparing the model, developers can now match the values ​​of Strings, enums, and records, which makes it much easier to write short and readable code. In traditional switch syntax, operators could only match the type of the variable, whereas, in lambda syntax, operators had to use if-else statements to match a value. Pattern matching for a switch provides an easy and efficient way to match values, making code more accurate and precise.

The syntax for pattern matching in Java is fairly straightforward and involves a ‘case’ keyword followed by an arrow (‘->’) to indicate what code should be executed if the pattern matches. In addition to matching on specific values, developers can also use pattern matching to perform more complex tasks, such as matching on specific records fields or matching on a range of values. Pattern matching for switch in Java is another exciting feature that will allow developers to write transparent and concise code, while also reducing the risk of errors. By matching real values, rather than just their types, developers can write more accurate and precise code, ultimately resulting in better software.

Traditional and Lambda Syntax

In Java, a switch statement allows you to test the value of a variable and execute different codes based on the value of that variable. Both the traditional and lambda syntax can be used to write switch statements in Java.

1. Traditional Syntax

The traditional syntax for a switch statement involves using the ‘switch’, ‘case’, ‘default’, and ‘break’ keywords. Here is an example:

Java




import java.io.*;
  
class GFG {
    public static void main(String[] args)
    {
      int num = 2;   // Initialize an integer variable named num with a value of 2
      String result; // Declare a String variable named result
  
      switch(num) {  // Start a switch statement using the value of num as the input
          case 1:    // If num is equal to 1, execute the code below
              result = "One"; // Set result to the String "One"
              break; // Exit the switch statement
          case 2:    // If num is equal to 2, execute the code below
              result = "Two"; // Set result to the String "Two"
              break; // Exit the switch statement
          case 3:    // If num is equal to 3, execute the code below
              result = "Three"; // Set result to the String "Three"
              break; // Exit the switch statement
          default:   // If none of the above cases match, execute the code below
              result = "Unknown"; // Set result to the String "Unknown"
              break; // Exit the switch statement
      }
      // Print the value of 
      // result to the console
      System.out.println(result);
    }
}


Output

Two

In summary, this code sets the value of the integer variable ‘num’ to 2, then uses a switch statement to check the value of ‘num’ and sets the value of the ‘result’ string variable accordingly. In this case, the value of num matches the second case (case 2:), so the result is set to the String “Two”. Finally, the value of the result is printed to the console using ‘System.out.println()’.

2. Lamba Syntax

In this example, we use a switch statement to determine the name of the day of the week based on the value of the ‘day’ variable. Each case specifies the value of the day to match, and the lambda expression after the arrow -> ‘ specifies the action to take if the value matches. The default case is executed if the value of the day is not in the range of 1-7.

Java




import java.io.*;
  
class GFG {
    public static void main(String[] args)
    {
        // Set the value of the day variable to 3
        int day = 3;
        // Use a switch statement to determine the name of
        // the day of the week
        switch (day) {
          case 1 -> System.out.println("Monday");   // If day equals 1, print "Monday"
          case 2 -> System.out.println("Tuesday");  // If day equals 2, print "Tuesday"
          case 3 -> System.out.println("Wednesday");// If day equals 3, print "Wednesday"
          case 4 -> System.out.println("Thursday"); // If day equals 4, print "Thursday"
          case 5 -> System.out.println("Friday");   // If day equals 5, print "Friday"
          case 6 -> System.out.println("Saturday"); // If day equals 6, print "Saturday"
          case 7 -> System.out.println("Sunday");   // If day equals 7, print "Sunday"
          default -> System.out.println("Invalid day"); // If day is not in the range 1-7, print "Invalid day"
        }
    }
}


Output 

Wednesday

Note: Lambda expressions were introduced in Java 8, so this code will only work if you are using Java 8 or later. If you are using an earlier version of Java, you will need to use the traditional syntax with colons and break statements.

Example 1: Matching on Strings

Traditional Syntax

Java




import java.io.*;
  
class GFG {
    public static void main(String args[])
    {
        // Create a string variable named 
          // "fruit" and initialize it to "banana"
        String fruit = "banana";
  
        // Use a switch statement to determine 
          // the value of the "fruit" variable
        switch (fruit) {
  
            // If the value of "fruit" is
            // "apple", execute this case
            case "apple":
                System.out.println("This is an apple.");
                break;
  
            // If the value of "fruit" is 
            // "banana", execute this case
            case "banana":
                System.out.println("This is a banana.");
                break;
  
            // If the value of "fruit" is "orange", 
            // execute this case
            case "orange":
                System.out.println("This is an orange.");
                break;
  
            // If the value of "fruit" is not "apple", 
            // "banana", or "orange", execute this case
            default:
                System.out.println("This is not an apple, banana, or orange.");
        }
    }
}


Lambda Syntax

Java




/*package whatever //do not write package name here */
  
import java.io.*;
  
class GFG {
    public static void main (String[] args) {
      // Create a string variable called "fruit" and assign it the value "banana".
      String fruit = "banana";
      // Use a switch statement to check the value of the "fruit" variable.
      // Depending on the value of "fruit", print out a different message.
      switch (fruit) {
        // If the value of "fruit" is "apple", print "This is an apple."
        case "apple" -> System.out.println("This is an apple.");
        // If the value of "fruit" is "banana", print "This is a banana."
        case "banana" -> System.out.println("This is a banana.");
        // If the value of "fruit" is "orange", print "This is an orange."
        case "orange" -> System.out.println("This is an orange.");
        // If the value of "fruit" is anything else, print
        // "This is not an apple, banana, or orange."
        default -> System.out.println("This is not an apple, banana, or orange.");
      }
    }
}


Output

This is a banana.

This code checks the value of the fruit variable using a switch statement, which allows the program to take different actions depending on the value of the variable. The case statements specify the possible values of fruit, and the ‘ -> ‘ arrow notation indicates what should happen if the value matches that case. If the value of fruit does not match any of the case statements, the default case is executed.

Example 2: Matching on Enum Constants 

Pattern matching in switch statements can also be combined with other Java features, such as enums and records. For example, developers can match on enum constants and record components using pattern matching.

Lambda Syntax

Java




import java.io.*;
  
class GFG {
    public static void main(String[] args)
    {
        enum Color { RED, GREEN, BLUE }
  
        Color color = Color.RED;
  
        // Match on the enum constant "color"
        switch (color) {
          // Match on the enum constant "RED"
          case RED -> System.out.println("The color is red."); 
          // Match on the enum constant "GREEN"
          case GREEN -> System.out.println("The color is green."); 
          // Match on the enum constant "BLUE"
          case BLUE -> System.out.println("The color is blue."); 
        }
    }
}


Output 

The color is red.

An enum (short for “enumeration”) in programming is a data type that represents a fixed set of values, often referred to as “enumerators” or “constants”. In the example code you provided, the Color enum defines a set of three possible values: RED, GREEN, and BLUE.

Using an enum in a switch statement allows you to handle each of the possible values of the enum differently, without the need for multiple if-else statements. In this case, the switch statement checks the value of the color variable and executes the corresponding case statement based on its value.

This code defines an enum called Color with three possible values: RED, GREEN, and BLUE. After defining the Color enum, the code sets a variable color to Color.RED. Then, a switch statement is used to check the value of the color variable. The switch statement uses the case keyword to specify what code should be executed for each possible value of the Color enum.

Conclusion

Developers should be aware of the limitations of pattern matching in switch statements, such as the fact that it only works on certain types of patterns and may not work as well as other methods. In addition, developers should be aware of the potential of unintended behavior or bugs when using the pattern matching in switch statements, especially when dealing with complex systems

Overall, pattern matching in switch statements is a powerful and useful tool that can improve code quality and readability. However, like any other part of programming, developers should weigh its advantages and disadvantages and use it properly in their programs.



Like Article
Suggest improvement
Previous
Next
Share your thoughts in the comments

Similar Reads