Java Help Case Statements Please

Hey, any help would be greatly appreciated.

For case statements, we add a break after each case else the code would run all the subsequent cases. Does anyone know why this is the case? Surely if we have the code below:

String role = “admin”;
switch (role) {
case “admin”:
System.out.println(“You’re an admin”);
break;

        case "moderator":
            System.out.println("You're a moderator");
            break;

        default:
            System.out.println("You're a guest");

and if we got rid of the break statements, surely Java would know that the moderator case and default case does not apply?

In essence, I’m wondering why it runs the other cases when the role is defined as admin when we remove the break statement. Apologises if this is a silly question, thanks for your time and help!

One advantage of this “fall through” behavior is that we can do things like

switch (role) {
  case "admin":
  case "super-admin":
    System.out.println("You're some kind of admin");
    break;
  case "moderator":
    System.out.println("You're a moderator");
    break;
  default:
    System.out.println("You're a guest");
}

The “admin” case falls through to the “super-admin” case and allows us to execute logic that is appropriate for any sort of admin when the role is “admin” or “super-admin”.

Also, Java 14 introduced the permanent feature of the new “enhanced” switch-case which has the behavior you want:

switch (role) {
  case "admin", "super-admin" -> System.out.println("You're some kind of admin");
  case "moderator" -> System.out.println("You're a moderator");
  default -> System.out.println("You're a guest");
}

It is documented here:

1 Like