When is an unassigned expression a valid statement?

前端 未结 4 734
一生所求
一生所求 2020-12-20 11:23

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 O         


        
相关标签:
4条回答
  • 2020-12-20 11:39

    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.

    0 讨论(0)
  • 2020-12-20 11:46

    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.

    0 讨论(0)
  • 2020-12-20 11:47

    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.

    0 讨论(0)
  • 2020-12-20 11:56

    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.

    0 讨论(0)
提交回复
热议问题