Unnamed Patterns

Patterns in Java are mainly associated with switch expressions and instanceof operators. Unnamed patterns that are introduced in Java 14 as preview features and made stable in Java 16 which extend the concept of patterns by allowing developers to match values without binding them to variables explicitly.

Example of Unnamed Pattern

It uses the underscore character ‘_’ as a wildcard to match any value without binding it to a variable. In the above example, the ‘_’ pattern matches any value of ‘x’ that is not explicitly handled by the previous cases. It acts as a wildcard pattern.

Below is an example of an Unnamed Pattern:

Java
// Define a class Person with a constructor
class Person {
    String name;
    int age;

    // Constructor with parameters for name and age
    Person(String name, int age) {
        this.name = name;
        this.age = age;
    }
}

// Driver Class
public class UnnamedPatterns {
    // Main Function
    public static void main(String[] args) {
        // Create an instance of the Person class
        Person person = new Person("Alice", 30);

        // Use pattern matching in an if statement
        if (person instanceof Person) {
            // Cast person to Person type to access its fields
            Person p = (Person) person;
            System.out.println("Person's name is: " + p.name);
        }

        // Another example with pattern matching and an
        // unnamed variable
        if (person instanceof Person && person.age > 20) {
            System.out.println("Person is older than 20 years old.");
        }
    }
}

Output
Person's name is: Alice
Person is older than 20 years old.

Unnamed Patterns and Variables in Java

Java programming language offers multiple features that allow developers to write rich and concise code. Among these features, there are unnamed patterns and variables which enables developers to work with data in a more flexible and elegant way.

In this article, we will study about unnamed patterns and variables in Java and how they can be used effectively.

Similar Reads

Unnamed variables

These are related features to unnamed patterns which allow developers to use placeholder variables without assigning names to them explicitly. This can be useful in various situations where a variable name is not necessary or the value of variable is not going to be used....

Unnamed Patterns

Patterns in Java are mainly associated with switch expressions and instanceof operators. Unnamed patterns that are introduced in Java 14 as preview features and made stable in Java 16 which extend the concept of patterns by allowing developers to match values without binding them to variables explicitly....

Frequently Asked Question

1. When Should I use unnamed patterns and variables?...