Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

368
Visualizações
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.

over 4 years ago · Santiago Trujillo
3 Respostas
Responde à pergunta

0

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.

over 4 years ago · Santiago Trujillo Relatório

0

IntelliJ recognises that you are trying to use a switch statement rather than a switch expression. If you change your code to be:

    int val = switch (day) {
        case MONDAY -> dog();
        case TUESDAY -> 2 + 2;
        case WEDNESDAY -> true;
        default -> System.out.println("");
    }

You will find that the error is now with the print statement and the true value because they cannot be converted to int. This is because Intellij now recognises your code as a switch expression.

In other words, all the branches of a switch expression need to be expressions of the same type and branches of a switch statement need to be statements. The method call dog() is both, hence it will work in either context.

over 4 years ago · Santiago Trujillo Relatório

0

The thing is that 2 + 2 and true are not Java statements. In the reference documentation we can read the following:

Statements are roughly equivalent to sentences in natural languages. A statement forms a complete unit of execution. The following types of expressions can be made into a statement by terminating the expression with a semicolon (;).

  • Assignment expressions
  • Any use of ++ or --
  • Method invocations
  • Object creation expressions

Such statements are called expression statements. Here are some examples of expression statements:

// assignment statement
aValue = 8933.234;

// increment statement
aValue++;

// method invocation statement
System.out.println("Hello World!");

// object creation statement
Bicycle myBike = new Bicycle();

2 + 2 and true are none of those since they are expressions instead, hence the compilation error in your switch statement.

over 4 years ago · Santiago Trujillo Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda