From the course: Java SE 17 Developer (1Z0-829) Cert Prep

Unlock this course with a free trial

Join today to access over 25,300 courses taught by industry experts.

Additional topics in pattern-matched instanceof

Additional topics in pattern-matched instanceof - Java Tutorial

From the course: Java SE 17 Developer (1Z0-829) Cert Prep

Additional topics in pattern-matched instanceof

- Let's take a look at the scope of our pattern variables. It turns out pattern variables are initialized only when instanceof yields true. We knew that. But the scope of these variables is accurately tracked to where they will have definitely been initialized. We need to be a little cautious perhaps with complex boolean expressions. But let's take a look at some code and you'll see the kinds of things I'm describing. So here's our most simple example. We have an object initialized to a String and we do an instanceof test to see if that object in fact refers to a String. But we also have a pattern String s to initialize s to refer to this same object if it is in fact string. And you'll notice in the positive side of the if test, we have s in scope, but if we try to print s out in the else side, it's not in scope. Which of course we would expect. If on the other hand, I invert the overall logic of the test, now s is not in scope in the if side, but it is in scope in the else side…

Contents