[HD-OCP17/21-Fundamentals Pg 242, Sec. 10.2.1 - using-instanceof-as-a-pattern-matching-operator]

Help and support on OCA OCP Java Programmer Certification Questions
1Z0-808, 1Z0-809, 1Z0-815, 1Z0-816, 1Z0-817

Moderator: admin

Post Reply
raphaelzintec
Posts: 167
Joined: Sun Apr 21, 2024 10:43 am
Contact:

[HD-OCP17/21-Fundamentals Pg 242, Sec. 10.2.1 - using-instanceof-as-a-pattern-matching-operator]

Post by raphaelzintec »

void main(String[] args){
Object obj = getObject(args.length);
if(! (obj instanceof String str) ){
//will not compile if return statement is commented out
return; //or a throw an exception!
}
System.out.println("str = "+str);
}

this out of scope has no real logic, it works only with ! operator and empty return.
Why i mean by that is that compiler doesnt care if its true or false, it will be correct

pheroidsmok
Posts: 1
Joined: Thu Sep 26, 2024 4:45 am
Contact:

Re: [HD-OCP17/21-Fundamentals Pg 242, Sec. 10.2.1 - using-instanceof-as-a-pattern-matching-operator]

Post by pheroidsmok »

raphaelzintec wrote:
Tue Sep 24, 2024 1:38 pm
void main(String[] args){
Object obj = getObject(args.length)geometry dash;
if(! (obj instanceof String str) ){
//will not compile if return statement is commented out
return; //or a throw an exception!
}
System.out.println("str = "+str);
}

this out of scope has no real logic, it works only with ! operator and empty return.
Why i mean by that is that compiler doesnt care if its true or false, it will be correct
Sorry, but I still don't really understand this code. How does the return statement work?

admin
Site Admin
Posts: 10388
Joined: Fri Sep 10, 2010 9:26 pm
Contact:

Re: [HD-OCP17/21-Fundamentals Pg 242, Sec. 10.2.1 - using-instanceof-as-a-pattern-matching-operator]

Post by admin »

The return statement ensures that there is no path left in the code that the control can take when obj is not an instance of String. Therefore, the compiler knows for sure that str will be in scope everywhere else. This is why str is available outside the if block.

Without the return statement, the print statement will be executed even when !(obj instanceof String str) is false. But in that case str will not be in flow scope and so the compiler refuses to accept this code.

Post Reply

Who is online

Users browsing this forum: No registered users and 6 guests