About Question enthuware.ocpjp.v21.2.3800 :

All the posts and topics that contain only an error report will be moved here after the error is corrected. This is to ensure that when users view a question in ETS Viewer, the "Discuss" button will not indicate the presence of a discussion that adds no value to the question.

Moderators: Site Manager, fjwalraven

Post Reply
Ganiyat
Posts: 2
Joined: Mon Nov 18, 2024 1:12 am
Contact:

About Question enthuware.ocpjp.v21.2.3800 :

Post by Ganiyat »

public int switchTest(byte x){
return switch(x){ //1
case 'b', 'c' -> 10; //2
case -2 -> 20; // 3
case 80, default -> 30; // 4
}; }
The explanation given for the above expression says that compilation will fail because of line 4. Because default cannot be combined with another case expression (case 80). However, the switch expression below was marked as a valid option. Considering the fact that the option also combines case null and default makes it confusing. Could you please explain? Thanks

String winLoseOrTie(Object obj){   
return switch(obj){   
  case Integer i       
when i<10 -> "lose";    
 case Integer i       
when i>10 -> "win";                    
 case Integer i       
when i==10 -> "tie";                                
 case null, default -> "invalid intput";   
}; }

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

Re: About Question enthuware.ocpjp.v21.2.3800 :

Post by admin »

Yes, you are right. Although the option is correctly marked as wrong the explanation is not right. It is true that default cannot be combined with any other case label in a regular switch statement/expression but "case null, default " is an exception allowed by the JLS and it is applicable only for a switch with pattern matching.

thank you for your feedback!

Ganiyat
Posts: 2
Joined: Mon Nov 18, 2024 1:12 am
Contact:

Re: About Question enthuware.ocpjp.v21.2.3800 :

Post by Ganiyat »

Thanks for this answer.

Post Reply

Who is online

Users browsing this forum: No registered users and 8 guests