Is Java evaluation order guaranteed in this case of method call and arguments passed in

大兔子大兔子 提交于 2019-12-01 17:41:28

The bit of the JLS you referred to (15.7.4) does guarantee that:

Each argument expression appears to be fully evaluated before any part of any argument expression to its right.

and also in 15.12.4.2:

Evaluation then continues, using the argument values, as described below.

The "appears to" part allows for some optimization, but it must not be visible. The fact that all the arguments are evaluated before "evaluation then continues" shows that the arguments are really fully evaluted before the method executes. (Or at least, that's the visible result.)

So for example, if you had code of:

int x = 10;
foo(x + 5, x + 20);

it would be possible to optimize that to evaluate both x + 5 and x + 20 in parallel: there's no way you could detect this occurring.

But in the case you've given, you would be able to detect the call to obj.myMethod occurring after the call to obj.myBoolean(), so that wouldn't be a valid optimization at all.

In short: you're fine to assume that everything will execute in the obvious way here.

In addition to the argument evaluation order, the overview of the steps preformed when invoking a method, and their order, explained in section 15.12.4. Run-Time Evaluation of Method Invocation, makes it clear that all argument evaluations are performed before executing the method's code. Quote:

At run time, method invocation requires five steps. First, a target reference may be computed. Second, the argument expressions are evaluated. Third, the accessibility of the method to be invoked is checked. Fourth, the actual code for the method to be executed is located. Fifth, a new activation frame is created, synchronization is performed if necessary, and control is transferred to the method code.

The case you presented where an argument is only evaluated after control has been transferred to the method code is out of the question.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!