Java Tutorial

Pattern Matching (JAVA 16+)

instanceof checks with direct bindings and modern switch logic

What is Pattern Matching in Java?

Introduced as a standard feature in JAVA 16, Pattern Matching is a powerful way to "extract" data from an object if it matches a specific type or structure.
Prior to this, you had to perform two separate steps (a check and a cast), which was repetitive and error-prone. With Pattern Matching, you do it in ONE line!
java
Object obj = "Hello, Java!";

// Modern Way!
if (obj instanceof String s) {
    // Variable 's' is already a String!
    System.out.println(s.toUpperCase());
}

Comparisons: The Old Way vs. The Modern Way

Wait! Why did we change this after 25 years?
  • Old: if (obj instanceof String) { String s = (String) obj; ... } (Repeating "String" three times!)
  • Modern: if (obj instanceof String s) { ... } (Check and bind in one step!)

Pattern Matching with switch (JAVA 17+)

Java's powerful switch statements can now also perform pattern matching! This is perfect for handling complex hierarchies of data (like different shapes or user roles).
java
static String getLabel(Object obj) {
    return switch (obj) {
        case Integer i -> "An Integer: " + i;
        case String s  -> "A String: " + s;
        case null      -> "Value is Null!";
        default        -> "Unknown Object.";
    };
}

Guiding Patterns: The when Clause (JAVA 21+)

You can even add extra logic (guards) to your pattern matching to make it even more precise.
java
return switch (obj) {
    case String s when s.length() > 10 -> "A LONG String!";
    case String s -> "A short string.";
    default -> "Unknown.";
};

Summary

TermDescription
instanceofType checking with automatic binding
PatternThe combination of a type + a variable name
BindingAutomatically creating a variable if the match is true
SwitchType-safe branching for many different data types
whenAdd extra logical "guards" to a match
Best ForProcessing mixed types, complex object handling
ModernJava 16 (instanceof), Java 17/21 (switch)
SafePrevents most "ClassCastException" bugs!
CleanRemoves repetitive (and boring!) boilerplate code
FinalThe bound variable (s) is implicitly final!
ScopeVariable only exists where the check is TRUE!
RecursivePattern matching can also unpack complex Records!
NullSwitch patterns now handle null cases explicitly!
StandardEstablished and trusted worldwide for 25+ years
ExhaustiveSwitch with patterns MUST handle all possible cases!
ReturnIdeal for returning different values from a complex logic
Recordcase User(String n, int a) (Modern unpacking!)
SealWorks perfectly with "Sealed Classes" (See below!)
SafetyCompiler will NOT let you use the variable if match fails!
LogicCode once; use for many different types!
IdentityAn object never "forgets" its real type internally
StructureJava folder structure MUST match the package name!
PackageOrganizes code into logical folders (namespaces)
LibraryA "Library" is a pre-written collection of packages
StaticImport methods/constants with import static
Wildcard* imports ONLY classes, not entire sub-packages!