Old way, new way, && and early return
Pattern matching for instanceof tests a value's type and, if it matches, gives you a ready-cast variable in the same step: if (o instanceof String s) { s.length(); }. It removes the repeated cast, and the compiler decides exactly where the new variable can be used.
Change the code and press Run (Ctrl+Enter). Try to predict the output first, then break it on purpose and read the error. Your edits are saved and match the lesson page.
Practice questions
Write the code in the editor, run it, then open the model answer to compare.
Write static int lengthOf(Object o) that returns the length of a String, the size of a java.util.Collection, the length of an int[], and -1 otherwise. Test it with "chai", List.of(1, 2, 3), new int[5] and 3.14.
Write static String firstWord(Object o) that returns "none" early if o is not a String or is blank, and otherwise returns the first word. Use a negated pattern with early return. Test with " hello world", " " and 42.
Write a final class Temperature with a double celsius field and an equals that uses a type pattern and Double.compare. Print new Temperature(36.6).equals(new Temperature(36.6)), .equals(null) and .equals("36.6").
Explain it without notes
What problem does pattern matching for instanceof solve, and when did it become standard?
Explain flow scoping with &&, || and an early return.
Why can the binding never be null?
Why does o instanceof List<String> l fail to compile when o is an Object?
What bytecode does o instanceof String s compile to, and is there a performance cost?
Expected output
text of length 6 | text of length 6
not text | not text
not text | not text
isLongWord("samosa"): true
isLongWord("tea"): false
isLongWord(null): false
CHAI!
can't shout 3.5