Search code examples
javaswitch-statementconditional-statementsswitch-expression

Why Switch requires statement but accepts expressions


I'm studying switch expressions and I think I found a weird behaviour:

public static boolean isTimeToParty(Day day) {
    switch (day) {
        case MONDAY -> dog(); //expression allowed
        case TUESDAY -> 2 + 2; //error: not a statement
        case WEDNESDAY -> true; //error: not a statement
        default -> System.out.println("");
    }
    return false;
}

public static int dog() {
    return 2;
}

Why can I type as value dog() which is an expression but other types of expression are not allowed? Intellij prompts me with "not a statement" error.

Thanks in advance.


Solution

  • A method invocation expression can also be used as a statement, as per the language specification:

    14.8. Expression Statements

    Certain kinds of expressions may be used as statements by following them with semicolons.
    ExpressionStatement:
    StatementExpression ;
    StatementExpression:
    Assignment
    PreIncrementExpression
    PreDecrementExpression
    PostIncrementExpression
    PostDecrementExpression
    MethodInvocation
    ClassInstanceCreationExpression

    The second last line indicates that a method invocation expression can be used as a statement, which is why dog() is accepted. The return value is simply discarded. 2 + 2 cannot be used as a statement.