logo

Java - Switch

Simple Example

Before Java 7, swtich can work with: byte/Byte, short/Short, char/Character, int/Integer, and enums.

public String getEvenOrOdd(int k) {
  String result;
  switch (k % 2) {
    case 0:
      result = "EVEN";
      break;
    case 1:
      result = "ODD";
      break;
    default:
      result = "NOT POSSIBLE";
  }
  return result;
}

Java 7+: Strings

After Java 7, String can be used as well.

public String getTypeOfDayWithSwitchStatement(String dayOfWeekArg) {
    String typeOfDay;
    switch (dayOfWeekArg) {
        case "Monday":
        case "Tuesday":
        case "Wednesday":
        case "Thursday":
        case "Friday":
            typeOfDay = "Weekday";
            break;
        case "Saturday":
        case "Sunday":
            typeOfDay = "Weekend";
            break;
        default:
            throw new IllegalArgumentException("Invalid day of the week: " + dayOfWeekArg);
    }
    return typeOfDay;
}

Java 12+

After Java 12, we can have multiple case labels, separated by comma ,; and no fall through, by using the new ->:

switch (day) {
    case MONDAY, FRIDAY, SUNDAY -> System.out.println(6);
    case TUESDAY                -> System.out.println(7);
    case THURSDAY, SATURDAY     -> System.out.println(8);
    case WEDNESDAY              -> System.out.println(9);
}

Previously switch is a statement, there's no return value, so a separate variable need to be kept. Now switch can also be used as an expression:

int numLetters = switch (day) {
    case MONDAY, FRIDAY, SUNDAY -> 6;
    case TUESDAY                -> 7;
    case THURSDAY, SATURDAY     -> 8;
    case WEDNESDAY              -> 9;
};

More can be found in JEP 325