java方法参数顺序,Java中方法调用和参数之间的评估顺序

Dealing with another SO question, I was wondering if the code below has an undefined behavior:

if (str.equals(str = getAnotherString())) {

// [...]

}

I tend to think the str reference from which the equals() call is made is evaluated before the further str assignment passed as argument. Is there a source about it?

解决方案

This is clearly specified in the JLS Section 15.12.4:

At run time, method invocation requires five steps. First, a target reference may be computed. Second, the argument expressions are evaluated. [...]

What's a "target reference" you ask? This is specified in the next subsection:

15.12.4.1. Compute Target Reference (If Necessary)

...

If form is ExpressionName . [TypeArguments] Identifier, then:

If the invocation mode is static, then there is no target reference. The ExpressionName is evaluated, but the result is then discarded.

Otherwise, the target reference is the value denoted by ExpressionName.

So the "target reference" is the str bit in str.equals - the expression on which you are calling the method.

As the first quote says, the target reference is evaluated first, then the arguments. Therefore, str.equals(str = getAnotherString()) only evaluates to true if getAnotherString returns a string that has the same characters as str before the assignment expression.

So yeah, the thing that you tend to think is correct. But this is not "undefined behaviour".

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值