Page 1 of 1

[HD-OCP17/21-Fundamentals Pg 247, Sec. 10.2.1 - using-multiple-pattern-variables]

Posted: Wed Jan 01, 2025 7:20 am
by raphaelzintec

Code: Select all

Number n = null;
//using instanceof for type comparison
if(n instanceof Number){ //valid for all versions, false if n is null
}
if(n instanceof Object){ //valid for all versions, false if n is null
}
//using instanceof for pattern matching
if(n instanceof Number num){ //compilation error in Java 17 but not in Java 21
}
if(n instanceof Object num){ //compilation error in Java 17 but not in Java 21
}

This is incorrect because the following will not give compilation error in Java 17
if(n instanceof Number num){ //compilation error in Java 17 but not in Java 21}

and honestly it would be more simplier to just say "In Java 17, you cannot use pattern matching with a supertype" period

Re: [HD-OCP17/21-Fundamentals Pg 247, Sec. 10.2.1 - using-multiple-pattern-variables]

Posted: Wed Jan 01, 2025 7:42 am
by admin
Which JDK are you using? Just tried it on JDK 17.0.3, it doesn't compile.

Re: [HD-OCP17/21-Fundamentals Pg 247, Sec. 10.2.1 - using-multiple-pattern-variables]

Posted: Wed Jan 01, 2025 9:50 am
by raphaelzintec
ok sorry

i was wrong about this: In Java 17, you cannot use pattern matching with a supertype

in short java 17 does not accept null for instanceof