且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

为什么我可以在不使用Java中返回值的情况下调用非空函数?

更新时间:2023-11-12 23:53:34

在诸如 main1 main2 之类的方法中,应该有语句.

In a method, such as main1 and main2, there are supposed to be statements.

MethodDeclaration:
    MethodHeader MethodBody
MethodBody:
    Block 
    ;

Block:
    { BlockStatements(opt) }

BlockStatements:
    BlockStatement
    BlockStatements BlockStatement

BlockStatement:
    LocalVariableDeclarationStatement
    ClassDeclaration
    Statement

500; 不是语句,但 Math.random(); 称为Fn(); 声明.

500; is not a statement, but Math.random(); and calledFn(); are statements.

让我们看看到底是什么构成了声明":

Let's see what exactly constitutes a "statement":

Statement:
    StatementWithoutTrailingSubstatement
    LabeledStatement
    IfThenStatement
    IfThenElseStatement
    WhileStatement
    ForStatement
StatementWithoutTrailingSubstatement:
    Block
    EmptyStatement
    ExpressionStatement
    AssertStatement
    SwitchStatement
    DoStatement
    BreakStatement
    ContinueStatement
    ReturnStatement
    SynchronizedStatement
    ThrowStatement
    TryStatement

要注意的重要一点是,存在一种称为表达式语句"的语句.让我们看看它的语法:

The important thing to note is that there is a kind of statement called an "expression statement". Let's see the syntax of that:

ExpressionStatement:
    StatementExpression ;

StatementExpression:
    Assignment
    PreIncrementExpression
    PreDecrementExpression
    PostIncrementExpression
    PostDecrementExpression
    MethodInvocation
    ClassInstanceCreationExpression

ExpressionStatement 只是一个 StatementExpression ,后跟一个; .请注意,并非所有的表达式都是 StatementExpression . 500 是一个文字,它是一种表达式,而不是 StatementExpression .另一方面, Math.random()称为Fn()是方法调用,它们是 StatementExpression

An ExpressionStatement is just a StatementExpression followed by a ;. Note that not all expressions are StatementExpressions. 500 is a literal, which is a kind of expression, but not a kind of StatementExpression. On the other hand, Math.random() and calledFn() are method invocations, which are StatementExpressions.

显示的所有语法均摘录自第18节语言规范的版本.

All the syntax shown are excerpts from section 18 of the Java Language Specification.

但是这两个函数不是完全一样吗?

But aren't both functions doing the exact same thing?

从语法上讲,它们不是.在 main2 的方法主体中,有一个文字,后跟一个; ,编译器无法将其识别为语句.在 main1 中,编译器将称为Fn()识别为方法调用,因此称为(Fn(); )的是一条语句.

Syntactically, they are not. In the method body of main2, there is a literal followed by a ;, which the compiler doesn't recognise as a statement. In main1, the compiler recognises calledFn() as a method invocation, and so calledFn(); is a statement.

作为人类,我们倾向于在精神上替代"人类.具有返回值的方法调用,但是编译器在解析代码时不会执行该操作.

As humans, we tend to mentally "replace" the method invocation with the value that it returns, but the compiler doesn't do that when parsing your code.