Java14 introduced pattern-matching changes to the instanceof method, to reduce explicit conversion.

an object is a superclass and holds data of any type. To convert or cast an Object to a different type, we will use instanceOf to check if an object is a given type.

For example, an Object holds a string value and needs the below things to call a string method on the object.

  • Check an instance is of a given type using instanceof method
  • Convert an object to String type by creating a local string variable
  • Call string methods on variable
public class PatternMatchingExample {

    public static void main(String[] args){
        // Object holds a string value
        Object object = "Object contains an string value";
        // Check if an object is a String or not
        if(object instanceof String){
            // convert object to a String
            String str = (String) object;
            // call string methods
            System.out.println(str.length());
        }
    }
}

The same code was rewritten by removing boilerplate code(casting) with simple pattern matching( obj instanceof String s)

pattern matching is a combination of a target type and a variable if a match is found.

The scope of the pattern-matching variable is within the enclosing braces.

public class Java14PatternMatchingExample {

    public static void main(String[] args){
        // Object holds a string value
        Object object = "Object contains an string value";
        // Check if an object is a String or not, and convert it to a String
        if(object instanceof String str && str.length>0){
            // call string methods
            System.out.println(str.length());
        }
    }
}

the variable is scoped within the braces and checks a variable is used in the local scope.

public class Java14PatternMatchingExample {

    public static void main(String[] args){
        // Object holds a string value
        Object object = "Object contains an string value";
        // Check if an object is a String or not, and convert it to a String
        if(object instanceof String str){
            // call string methods
            System.out.println(str.length());
        }
    }
}

In Summary, These changes allow you to reduce the explicit casts, and boilerplate code and make developers’ life easy.

You can check more about JEP-305