When is an unassigned expression a valid statement?

前端 未结 4 757
一生所求
一生所求 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: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.

提交回复
热议问题