Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

When is an unassigned expression a valid statement?

Tags:

java

I've read Oracle's expressions tutorial and couldn't understand this.

It is well known that the following line of code is valid Java syntax:

new Object();

However, when I try this with a primitive expression:

(3 + 2);

Eclipse is showing a compile error of "The left-hand side of an assignment must be a variable".

This is true not only for primitives, but also for String literals:

"arbitraryString";

So what is the rule for an unassigned expression to be valid as a Java line of code?

like image 252
unlimitednzt Avatar asked Sep 04 '15 20:09

unlimitednzt


4 Answers

The rule is in the Java 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

You see that a constructor invocation is a statement. But a String literal or mathematical expression is not.

like image 64
JB Nizet Avatar answered Oct 22 '22 03:10

JB Nizet


Creating an object or calling or method can have side effects, I think this is the main reason for this, whereas nothing will ever happen with an arithmetic expression.

like image 29
Dici Avatar answered Oct 22 '22 02:10

Dici


Line containing only

new Object(); 

or to be more precise

new SomeClass(); 

is acceptable, because code of SomeClass() constructor may be all we want.

But in case of lines containing only

"foo";

or

2;//or (2+3);

compiler knows that beside creating/reusing String literal or integer literal this code doesn't do anything else, which means it is probably some kind of programmer mistake so compiler can't accept it.

like image 21
Pshemo Avatar answered Oct 22 '22 03:10

Pshemo


You're looking for the difference between expressions and expression-statements. Statements like myVoid(); can be written as a statement: these are void methods, etc. (that's the part you know). Expressions, like (3 + 2); and "arbitraryString", have no side-effects. They can only be treated as a value, as no code is executed. Expression-statements, like new Object(); can have side-effects and execute code, and you sometimes just want this code to be executed and ignore the returned value. The compiler therefore allows this.

like image 35
bcsb1001 Avatar answered Oct 22 '22 02:10

bcsb1001