The instanceof operator tests whether an object is an instance of a type. Before pattern matching, a test was usually followed by a cast: if (obj instanceof String) { String s = (String) obj; ... }. Pattern matching combines the test, the cast and the variable declaration: if (obj instanceof String s) { ... }. If the test succeeds, s is a String variable ready to use. If obj is null, instanceof is false and nothing is bound.
Keep reading for free
Create a free StudyToCert account to read the rest of this lesson: 6 more sections, 4 key terms, a real-world example, an exam tip and self-check questions. Every lesson, lab and practice test is free with an account.