hi,
regarding the second answer:
switch(x){
case 2 -> {
System.out.print("A");
break; //redundant but allowed
}
case 3 -> System.out.print("B");
//break; //break not allowed here
default -> System.out.print("C"); //default is not necessary in a switch statement
}
Where it says "//redundant but allowed", shouldn't there be a yield statement as its in {}? I am thinking specifically with java 17 only.
Thanks
About Question enthuware.ocpjp.v17.2.3708 :
Moderator: admin
-
- Posts: 2
- Joined: Thu Oct 31, 2024 11:03 am
- Contact:
-
- Posts: 2
- Joined: Thu Oct 31, 2024 11:03 am
- Contact:
Re: About Question enthuware.ocpjp.v17.2.3708 :
In addition, the last comment:
default -> System.out.print("C"); //default is not necessary in a switch statement
This is sometimes necessary to include the default, right?
default -> System.out.print("C"); //default is not necessary in a switch statement
This is sometimes necessary to include the default, right?
-
- Site Admin
- Posts: 10384
- Joined: Fri Sep 10, 2010 9:26 pm
- Contact:
Re: About Question enthuware.ocpjp.v17.2.3708 :
No, a switch statement doesn't return any value and so a switch statement must not have yield. Only a switch expression returns a value and if you use { } then you need a yield.Where it says "//redundant but allowed", shouldn't there be a yield statement as its in {}? I am thinking specifically with java 17 only.
No, in Java 17, a switch statement does not need to have a default case because a switch statement does not need to be exhaustive.default -> System.out.print("C"); //default is not necessary in a switch statement
This is sometimes necessary to include the default, right?
In Java 17, only a switch expression has to be exhaustive and it may need a default if the rest of the cases do not cover all possibilities.
A switch statement with patterns (which is in Java 21) has to be exhaustive and in that case a default may be required if the rest of the case conditions do not cover all possibilities.
Who is online
Users browsing this forum: Bing [Bot] and 14 guests