Use Pattern Matching for instanceof

Inspections can guide us to use newer Java features.

If our code uses an instanceof followed by a cast, IntelliJ IDEA highlights these with a warning and suggests replacing this with pattern matching for instanceof. Note that this is only available if you're using a language level of Java 16 or above.

Press ⌥⏎ (macOS) / Alt+Enter (Windows/Linux) and choose Replace with pattern variable.

public class PatternMatchingSwitch {

 void outputValueInUpperCase(Object obj) {
  if (obj instanceof String) {
   String s = (String) obj;
   System.out.println(s);
  }
 }
}

You can press ⌥⏎ (macOS) / Alt+Enter (Windows/Linux) and choose Replace 's' with pattern variable.

public class PatternMatchingSwitch {

    void outputValueInUpperCase(Object obj) {
        if (obj instanceof String s) {
            System.out.println(s);
        }
    }
}

Interested in JVM Development?

call to action image

You can also use pattern matching for switch statements!

Learn More


Related Resources

Convert Class to Record
Convert Class to Record
Use inspections to convert classes to Java 16 records.
Run inspection
Run inspection
Run inspection by name. For example, run Vulnerable API usage to see where the vulnerable API of external dependencies is used in your code.
Vulnerable API Usage
Vulnerable API Usage
See whether you are using the vulnerable API of a dependency.