Pattern Matching for Switch in Java
Last Updated :
23 Jul, 2025
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);
}
}
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.");
}
}
}
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.
Similar Reads
Java Tutorial Java is a high-level, object-oriented programming language used to build web apps, mobile applications, and enterprise software systems. Known for its Write Once, Run Anywhere capability, which means code written in Java can run on any device that supports the Java Virtual Machine (JVM).Syntax and s
10 min read
Basics
Introduction to JavaJava is a high-level, object-oriented programming language developed by Sun Microsystems in 1995. It is platform-independent, which means we can write code once and run it anywhere using the Java Virtual Machine (JVM). Java is mostly used for building desktop applications, web applications, Android
4 min read
Java Programming BasicsJava is one of the most popular and widely used programming language and platform. A platform is an environment that helps to develop and run programs written in any programming language. Java is fast, reliable and secure. From desktop to web applications, scientific supercomputers to gaming console
4 min read
Java MethodsJava Methods are blocks of code that perform a specific task. A method allows us to reuse code, improving both efficiency and organization. All methods in Java must belong to a class. Methods are similar to functions and expose the behavior of objects.Example: Java program to demonstrate how to crea
7 min read
Access Modifiers in JavaIn Java, access modifiers are essential tools that define how the members of a class, like variables, methods, and even the class itself, can be accessed from other parts of our program. They are an important part of building secure and modular code when designing large applications. In this article
6 min read
Arrays in JavaIn Java, an array is an important linear data structure that allows us to store multiple values of the same type. Arrays in Java are objects, like all other objects in Java, arrays implicitly inherit from the java.lang.Object class. This allows you to invoke methods defined in Object (such as toStri
9 min read
Java StringsIn Java, a String is the type of object that can store a sequence of characters enclosed by double quotes and every character is stored in 16 bits, i.e., using UTF 16-bit encoding. A string acts the same as an array of characters. Java provides a robust and flexible API for handling strings, allowin
8 min read
Regular Expressions in JavaIn Java, Regular Expressions or Regex (in short) in Java is an API for defining String patterns that can be used for searching, manipulating, and editing a string in Java. Email validation and passwords are a few areas of strings where Regex is widely used to define the constraints. Regular Expressi
7 min read
OOPs & Interfaces
Classes and Objects in JavaIn Java, classes and objects are basic concepts of Object Oriented Programming (OOPs) that are used to represent real-world concepts and entities. A class is a template to create objects having similar properties and behavior, or in other words, we can say that a class is a blueprint for objects.An
10 min read
Java ConstructorsIn Java, constructors play an important role in object creation. A constructor is a special block of code that is called when an object is created. Its main job is to initialize the object, to set up its internal state, or to assign default values to its attributes. This process happens automaticall
10 min read
Java OOP(Object Oriented Programming) ConceptsBefore Object-Oriented Programming (OOPs), most programs used a procedural approach, where the focus was on writing step-by-step functions. This made it harder to manage and reuse code in large applications.To overcome these limitations, Object-Oriented Programming was introduced. Java is built arou
10 min read
Java PackagesPackages in Java are a mechanism that encapsulates a group of classes, sub-packages and interfaces. Packages are used for: Prevent naming conflicts by allowing classes with the same name to exist in different packages, like college.staff.cse.Employee and college.staff.ee.Employee.They make it easier
8 min read
Java InterfaceAn Interface in Java programming language is defined as an abstract type used to specify the behaviour of a class. An interface in Java is a blueprint of a behaviour. A Java interface contains static constants and abstract methods. Key Properties of Interface:The interface in Java is a mechanism to
11 min read
Collections
Exception Handling
Java Exception HandlingException handling in Java is an effective mechanism for managing runtime errors to ensure the application's regular flow is maintained. Some Common examples of exceptions include ClassNotFoundException, IOException, SQLException, RemoteException, etc. By handling these exceptions, Java enables deve
8 min read
Java Try Catch BlockA try-catch block in Java is a mechanism to handle exceptions. This make sure that the application continues to run even if an error occurs. The code inside the try block is executed, and if any exception occurs, it is then caught by the catch block.Example: Here, we are going to handle the Arithmet
4 min read
Java final, finally and finalizeIn Java, the keywords "final", "finally" and "finalize" have distinct roles. final enforces immutability and prevents changes to variables, methods, or classes. finally ensures a block of code runs after a try-catch, regardless of exceptions. finalize is a method used for cleanup before an object is
4 min read
Chained Exceptions in JavaChained Exceptions in Java allow associating one exception with another, i.e. one exception describes the cause of another exception. For example, consider a situation in which a method throws an ArithmeticException because of an attempt to divide by zero.But the root cause of the error was an I/O f
3 min read
Null Pointer Exception in JavaA NullPointerException in Java is a RuntimeException. It occurs when a program attempts to use an object reference that has the null value. In Java, "null" is a special value that can be assigned to object references to indicate the absence of a value.Reasons for Null Pointer ExceptionA NullPointerE
5 min read
Exception Handling with Method Overriding in JavaException handling with method overriding in Java refers to the rules and behavior that apply when a subclass overrides a method from its superclass and both methods involve exceptions. It ensures that the overridden method in the subclass does not declare broader or new checked exceptions than thos
4 min read
Java Advanced
Java Multithreading TutorialThreads are the backbone of multithreading. We are living in the real world which in itself is caught on the web surrounded by lots of applications. With the advancement in technologies, we cannot achieve the speed required to run them simultaneously unless we introduce the concept of multi-tasking
15+ min read
Synchronization in JavaIn multithreading, synchronization is important to make sure multiple threads safely work on shared resources. Without synchronization, data can become inconsistent or corrupted if multiple threads access and modify shared variables at the same time. In Java, it is a mechanism that ensures that only
10 min read
File Handling in JavaIn Java, with the help of File Class, we can work with files. This File Class is inside the java.io package. The File class can be used to create an object of the class and then specifying the name of the file.Why File Handling is Required?File Handling is an integral part of any programming languag
6 min read
Java Method ReferencesIn Java, a method is a collection of statements that perform some specific task and return the result to the caller. A method reference is the shorthand syntax for a lambda expression that contains just one method call. In general, one does not have to pass arguments to method references.Why Use Met
9 min read
Java 8 Stream TutorialJava 8 introduces Stream, which is a new abstract layer, and some new additional packages in Java 8 called java.util.stream. A Stream is a sequence of components that can be processed sequentially. These packages include classes, interfaces, and enum to allow functional-style operations on the eleme
15+ min read
Java NetworkingWhen computing devices such as laptops, desktops, servers, smartphones, and tablets and an eternally-expanding arrangement of IoT gadgets such as cameras, door locks, doorbells, refrigerators, audio/visual systems, thermostats, and various sensors are sharing information and data with each other is
15+ min read
JDBC TutorialJDBC stands for Java Database Connectivity. JDBC is a Java API or tool used in Java applications to interact with the database. It is a specification from Sun Microsystems that provides APIs for Java applications to communicate with different databases. Interfaces and Classes for JDBC API comes unde
12 min read
Java Memory ManagementJava memory management is the process by which the Java Virtual Machine (JVM) automatically handles the allocation and deallocation of memory. It uses a garbage collector to reclaim memory by removing unused objects, eliminating the need for manual memory managementJVM Memory StructureJVM defines va
4 min read
Garbage Collection in JavaGarbage collection in Java is an automatic memory management process that helps Java programs run efficiently. Java programs compile to bytecode that can be run on a Java Virtual Machine (JVM). When Java programs run on the JVM, objects in the heap are created, which is a portion of memory dedicated
7 min read
Memory Leaks in JavaIn programming, a memory leak happens when a program keeps using memory but does not give it back when it's done. It simply means the program slowly uses more and more memory, which can make things slow and even stop working. Working of Memory Management in JavaJava has automatic garbage collection,
3 min read
Practice Java
Java Interview Questions and AnswersJava is one of the most popular programming languages in the world, known for its versatility, portability, and wide range of applications. Java is the most used language in top companies such as Uber, Airbnb, Google, Netflix, Instagram, Spotify, Amazon, and many more because of its features and per
15+ min read
Java Programs - Java Programming ExamplesIn this article, we will learn and prepare for Interviews using Java Programming Examples. From basic Java programs like the Fibonacci series, Prime numbers, Factorial numbers, and Palindrome numbers to advanced Java programs.Java is one of the most popular programming languages today because of its
8 min read
Java Exercises - Basic to Advanced Java Practice Programs with SolutionsLooking for Java exercises to test your Java skills, then explore our topic-wise Java practice exercises? Here you will get 25 plus practice problems that help to upscale your Java skills. As we know Java is one of the most popular languages because of its robust and secure nature. But, programmers
7 min read
Java Quiz | Level Up Your Java SkillsThe best way to scale up your coding skills is by practicing the exercise. And if you are a Java programmer looking to test your Java skills and knowledge? Then, this Java quiz is designed to challenge your understanding of Java programming concepts and assess your excellence in the language. In thi
1 min read
Top 50 Java Project Ideas For Beginners and Advanced [Update 2025]Java is one of the most popular and versatile programming languages, known for its reliability, security, and platform independence. Developed by James Gosling in 1982, Java is widely used across industries like big data, mobile development, finance, and e-commerce.Building Java projects is an excel
15+ min read