Use Pattern Matching for instanceof

Inspections can guide us to use new 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);
        }
    }
}

Related Resources

Go to Next Error
Quickly move to the next (or previous) error or warning in the file.
Context Actions
Use Alt+Enter to show available context actions
Inspections Widget
The top-right corner of your editor shows you information about the state of your class