Page 1 of 1

About Question enthuware.ocpjp.v17.2.3708 :

Posted: Thu Oct 31, 2024 11:05 am
by herondinho1
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

Re: About Question enthuware.ocpjp.v17.2.3708 :

Posted: Thu Oct 31, 2024 11:08 am
by herondinho1
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?

Re: About Question enthuware.ocpjp.v17.2.3708 :

Posted: Thu Oct 31, 2024 8:58 pm
by admin
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, 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.

default -> System.out.print("C"); //default is not necessary in a switch statement
This is sometimes necessary to include the default, right?
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.
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.