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";
}; }
About Question enthuware.ocpjp.v21.2.3800 :
Moderators: Site Manager, fjwalraven
-
- Posts: 2
- Joined: Mon Nov 18, 2024 1:12 am
- Contact:
-
- Site Admin
- Posts: 10384
- Joined: Fri Sep 10, 2010 9:26 pm
- Contact:
Re: About Question enthuware.ocpjp.v21.2.3800 :
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!
thank you for your feedback!
-
- Posts: 2
- Joined: Mon Nov 18, 2024 1:12 am
- Contact:
Re: About Question enthuware.ocpjp.v21.2.3800 :
Thanks for this answer.
Who is online
Users browsing this forum: No registered users and 6 guests