Scrivio Interview library
CodingFoundations6 min read · updated 12 November 2026

Rewrite using pattern matching for instanceof and explain the scope of the binding variable:

Java
if (obj instanceof String) {
String s = (String) obj;
if (s.length() > 3) return s.toUpperCase();
}

The rewrite is if (obj instanceof String s && s.length() > 3) return s.toUpperCase();. The binding variable s exists only where the compiler can prove the match succeeded, which is called flow scoping: after && it is in scope, after || it is not, and after if (!(obj instanceof String s)) return; it is in scope for the rest of the block. Pattern matching for instanceof has been final since Java 16 (JEP 394).

Why this question is asked

The test-then-cast idiom, check instanceof, then cast, then use, is so common that most of us type it without thinking, and it has a small trap: the type is written three times and the cast can drift away from the check. Pattern matching for instanceof removes the duplication. Interviewers ask this question to see that we can do the rewrite and, more importantly, that we understand where the new variable can be used, because the scope rule is different from anything else in Java. In this answer, we will rewrite the code, see how the binding works, go through flow scoping with &&, || and negation, and look at a few details that trip people up.

1The Code Before

The original code checks the type, casts into a new variable, and then uses it.

Java
if (obj instanceof String) {
String s = (String) obj; // the cast repeats the type from the check
if (s.length() > 3) {
return s.toUpperCase();
}
}

Notice that String appears three times. If someone later changes the check to CharSequence and forgets the cast, the code still compiles and throws ClassCastException at run time for a StringBuilder. The compiler had all the information to do the cast for us, but the language gave it no way to.

2The Rewrite With a Type Pattern

A type pattern combines the check and the declaration: obj instanceof String s tests whether obj is a String, and if it is, declares s of type String already holding obj. We can then use s in the same condition.

Java
if (obj instanceof String s && s.length() > 3) {
return s.toUpperCase();
}
// results
// obj = "java" -> "JAVA"
// obj = "abc" -> condition false, falls through
// obj = 42 -> instanceof false, s is never assigned, falls through
// obj = null -> instanceof false for null, falls through

The type is written once, the cast is gone, and the two nested ifs become one. Notice that null needs no special handling: instanceof is always false for null, so the pattern never matches and s is never used. The feature was previewed in Java 14 and 15 and became final in Java 16 through JEP 394, so every LTS from Java 17 on has it.

3Flow Scoping: Where s Exists

A binding variable is not scoped like a normal local variable, which lives from its declaration to the end of the block. Instead, s is in scope exactly where the compiler can prove that the match succeeded. This is called flow scoping. The rules follow the logic of the boolean operators.

Java
if (obj instanceof String s && s.length() > 3) { } // OK: right of && runs only if the match succeeded
if (obj instanceof String s || s.length() > 3) { } // compile error: cannot find symbol s
// right of || runs when the match FAILED
if (obj instanceof String s) {
System.out.println(s.length()); // OK: inside the true branch
} else {
System.out.println(s); // compile error: s not in scope here
}
Step throughIs s in scope?
  1. Evaluate obj instanceof String ss assigned only if true
  2. Joined with && to the next condition?
    Yess usable on the right sideNoCheck the operator
  3. Joined with ||?
    Yess not usable on the right sideNoCheck the statement
  4. Inside the if's then branch?
    Yess usableNoNot usable in else
  5. Negated, and the if always exits?
    Yess usable after the ifNos not usable after it

5 steps in order. Play them, or step through them one at a time.

The binding exists wherever the match is known to have succeeded.

For &&, the right side runs only when the left side was true, so the match succeeded and s is definitely assigned. For ||, the right side runs only when the left side was false, which is exactly when there is no String, so s cannot be used there. The same reasoning places s inside the then branch of an if and not inside the else branch.

4The Negated Early Return

The most useful consequence of flow scoping is the guard clause. If we negate the pattern and leave the method when it does not match, the compiler knows that every statement after the if runs only when the match succeeded, so s stays in scope for the rest of the block.

Java
String shout(Object obj) {
if (!(obj instanceof String s)) {
return "not a string";
}
// from here on, s is a String
if (s.length() <= 3) {
return s;
}
return s.toUpperCase();
}
System.out.println(shout("hello")); // HELLO
System.out.println(shout("hi")); // hi
System.out.println(shout(7)); // not a string

This only works because the if block cannot complete normally: it returns. If the block could fall through, for example if it only logged a message, s would not be in scope afterwards, because the code after the if could then run without a match. The same applies to throw, break and continue.

5Details That Trip People Up

A binding variable cannot have the same name as a local variable already in scope, because that would shadow it; the compiler reports that the variable is already defined. A binding can, however, shadow a field, which is legal but confusing, so it is worth avoiding. Bindings are not implicitly final; we may reassign them, though there is rarely a good reason, and since Java 16 we may declare them final if we like.

Before Java 21, writing obj instanceof String s where obj's static type was already String was a compile error, because the type test was pointless: it could fail only for null. Java 21 relaxed that rule for patterns, so check your release if code must compile on Java 17. Finally, the same type patterns are used in switch since Java 21, with the same flow scoping inside each case, so learning these rules once pays off twice.

6Follow-up questions

Is pattern matching for instanceof slower than the explicit cast?

No. The compiler generates essentially the same bytecode as the check followed by a cast, and the JIT optimizes it the same way. The benefit is purely in correctness and readability.

Can we use a record pattern with instanceof?

Yes, since Java 21. For a record Point(int x, int y), the test obj instanceof Point(int x, int y) both checks the type and extracts the components into x and y, with the same flow scoping rules for the bindings.

Why does instanceof return false for null instead of throwing?

Because instanceof asks whether the value is an instance of the type, and null is not an instance of anything. That has always been true in Java, and pattern matching keeps it, so patterns never bind null.

7Conclusion

In this answer, we rewrote the test-then-cast code as if (obj instanceof String s && s.length() > 3) return s.toUpperCase();, removing the repeated type and the cast. We saw that the binding s is flow scoped: it is available after && and inside the then branch, not after || or in the else branch, and after a negated check whose block always exits it stays in scope for the rest of the block. instanceof patterns have been final since Java 16 through JEP 394, and null never matches.

What to say in the interviewAbout 100 seconds aloud

Open with

I would write it as if obj instanceof String s and s.length() greater than 3, return s.toUpperCase(). The type pattern does the check, the cast and the declaration in one step, so String is written once instead of three times, and the cast can never drift away from the check.

Then, if they want more

Null is handled automatically, because instanceof is false for null, so s is never bound. The interesting part is the scope of s. It is flow scoped, meaning it exists only where the compiler can prove the match succeeded.

On the right side of &&, that is true, because the right side only runs if the left side was true, so I can call s.length() there. On the right side of ||, it is not, because the right side runs when the match failed, so using s is a compile error.

In an if statement, s is available in the then branch and not in the else branch. And the pattern I use most is the guard clause: if not obj instanceof String s, return.

Because that block always exits, the compiler knows the rest of the method only runs after a successful match, so s stays in scope for the rest of the block. That only works if the block cannot complete normally, through return, throw, break or continue.

Pattern matching for instanceof was finalized in Java 16 with JEP 394, so it is available on every LTS from 17.

About this answer

Last updated
12 November 2026
Versions it names
Java 16, Java 21, Java 17, Java 14
Checked
Its structure and format are checked automatically. Use it as a carefully prepared study note: where a detail matters, confirm it against the documentation below. What the checks cover
Where the question comes from
Written by Scrivio for practice. It is not taken from an interview.
Report an issue with this answer

Copy the line below and send it to the author with what you found. It carries the address of this page.

Issue with "Rewrite using pattern matching for instanceof and explain the scope of the binding...": https://scrivio-interview-library.netlify.app/java/sealed-and-pattern-matching/c966511a6d/