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.
CodePudding user response:
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.
CodePudding user response:
A method invocation expression can also be used as a statement, as per the language specification:
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.
CodePudding user response:
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.
CodePudding user response:
The switch is in a statement context. A statement might also be a method call, discarding away its result. There also exists the switch expression, where the requirements are reversed.