To reduce duplication (boilerplate) in code pattern matching with if statements and the instanceof operator was introduced with Java version 16.

Pattern matching is a technique of controlling program flow that only executes a section of code that meets certain criteria.

Pattern matching with if and instanceOf

In code example without pattern matching cast is needed.


public Integer objectToString(Object object) {
        if (object instanceof String) {
            String string = (String) object;
            return Integer.parseInt(string);
        }
        if (object instanceof Integer) {
            return (Integer) object;
        }
        return 0;
    }
    

With pattern matching we get immediate cast.

public Integer objectToString(Object object) {
        if (object instanceof String strData) {
            return Integer.parseInt(strData);
        }
        if (object instanceof Integer intData) {
            return intData;
        }
        return 0;
    }

strData and intData are pattern variables here.

Pattern matching in switch

Pattern matching withing switch expression is supported by Java 17 but only as a Preview feature.

Same functionality with switch expression will look like:

public Integer objectToString(Object object) {
        return switch (object) {
            case String strData -> Integer.parseInt(strData);
            case Integer intData -> intData;
            default -> 0;
        };
    }