Page 1 of 1

About Question enthuware.ocpjp.v21.2.3800 :

Posted: Tue Nov 26, 2024 1:07 am
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";   
}; }

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

Posted: Tue Nov 26, 2024 7:48 am
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!

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

Posted: Wed Nov 27, 2024 3:31 am
by Ganiyat
Thanks for this answer.