Does a void method call count as an expression?

Viewed 123

In this Java docs tutorial: https://docs.oracle.com/javase/tutorial/java/nutsandbolts/expressions.html

System.out.println(), which is a void method call does not count as an expression, but in this link from the specs: https://docs.oracle.com/javase/tutorial/java/nutsandbolts/expressions.html

It is said that an expression can be something that evaluates to nothing (void). This leads to my question and confusion about if a void method call would count as an expression or not in Java? What is the reasoning behind it as well?

1 Answers

A call to a void method is still an expression. All method invocations are (primary) expressions, as specified by the production rule:

Primary:
  PrimaryNoNewArray 
  ArrayCreationExpression
PrimaryNoNewArray:
  Literal 
  ClassLiteral 
  this 
  TypeName . this 
  ( Expression ) 
  ClassInstanceCreationExpression 
  FieldAccess 
  ArrayAccess 
  MethodInvocation <----
  MethodReference

It's just that other rules in the language makes you unable to do much with it. Such an expression is of type void. You can't declare a variable of type void. void does not have any members, etc.

One place where the fact that void method calls are expressions becomes important is in lambda expression bodies. Consider the production rule:

LambdaBody:
  Expression 
  Block

If void method calls were not expressions, you would not be able to write:

Runnable r = () -> System.out.println();

The above only works because System.out.println() is an expression and hence can be used as a lambda body. If it were not an expression, you would have to use a block:

Runnable r = () -> { System.out.println(); };

At the end of the day, expressions are a syntactic thing, and at the syntactic level, the parser can't tell the return type of methods anyway :D.

Related