0

Why is this failing to compile with an error of "case expressions must be constant expressions"? Isn't null a constant (known at compile time)? Explicitly casting the null value to String as in case ((String)null) does not help too (I get the same error).

public static String getTypeOfDayWithSwitchStatement(String dayOfWeekArg) {
    String typeOfDay;
    switch (dayOfWeekArg) {

        case null:
            typeOfDay = "NULL";
            break;

        case "Monday":
            typeOfDay = "Start of work week";
            break;
        case "Tuesday":
        case "Wednesday":
        case "Thursday":
            typeOfDay = "Midweek";
            break;
        case "Friday":
            typeOfDay = "End of work week";
            break;
        case "Saturday":
        case "Sunday":
            typeOfDay = "Weekend";
            break;
        default:
            throw new IllegalArgumentException("Invalid day of the week: " + dayOfWeekArg);
    }
    return typeOfDay;
}
peter.petrov
  • 38,363
  • 16
  • 94
  • 159

2 Answers2

9

Yes, the case expressions must be constant expressions, but null is specifically prohibited by the JLS, Section 14.11, which describes the switch statement:

Given a switch statement, all of the following must be true or a compile-time error occurs:

  • Every case constant associated with the switch statement must be assignment compatible with the type of the switch statement's Expression (§5.2).

  • If the type of the switch statement's Expression is an enum type, then every case constant associated with the switch statement must be an enum constant of that type.

  • No two of the case constants associated with the switch statement have the same value.

  • No case constant associated with the switch statement is null.

  • At most one default label is associated with the switch statement.

(italics emphasis mine)

As a workaround, you can test for null outside of the switch statement.

Community
  • 1
  • 1
rgettman
  • 176,041
  • 30
  • 275
  • 357
-1

The switch statement will throw a NullPointerException if you pass it a null value. Use a separate test to check for null values.

markspace
  • 10,621
  • 3
  • 25
  • 39
  • 1
    It will indeed throw NPE but I have to compile it first (e.g. by removing that case null statement). So I find this relevant too. Thanks. – peter.petrov May 18 '15 at 22:35