Command Palette

Search for a command to run...

Back to the lesson: Topic 11.1 — Pattern Matching for instanceof
Core Java · Example 3 of 3 Java 16+

Scope, shadowing and reassignment

Shadowing a field with a binding is legal but confusing. It's shown here so you recognise it, not as a style to copy.

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.

01

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.

02

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.

03

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

01

What problem does pattern matching for instanceof solve, and when did it become standard?

02

Explain flow scoping with &&, || and an early return.

03

Why can the binding never be null?

04

Why does o instanceof List<String> l fail to compile when o is an Object?

05

What bytecode does o instanceof String s compile to, and is there a performance cost?

Scope, shadowing and reassignment Java 16+
Sign in to run this example in your browser.

Expected output

inside if: pattern
after if: field
inside else: field
after if: field
doubled: 42
final binding: 21