About Question enthuware.ocpjp.v17.2.3708 :

Help and support on OCA OCP Java Programmer Certification Questions
1Z0-808, 1Z0-809, 1Z0-815, 1Z0-816, 1Z0-817

Moderator: admin

Post Reply
herondinho1
Posts: 2
Joined: Thu Oct 31, 2024 11:03 am
Contact:

About Question enthuware.ocpjp.v17.2.3708 :

Post 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

herondinho1
Posts: 2
Joined: Thu Oct 31, 2024 11:03 am
Contact:

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

Post 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?

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

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

Post 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.

Post Reply

Who is online

Users browsing this forum: No registered users and 8 guests