String foo = null;
if(foo == null || foo.equals("")){
//this is only safe if I'm guaranteed that the evaluation happens from left to right
}
在Java中,有这样的保证吗?或者我是否需要同时执行这些测试才能确定?
最佳答案
是的。来自 JLS section 15.24 :
The conditional-or operator
||
operator is like|
(§15.22.2), but evaluates its right-hand operand only if the value of its left-hand operand is false.
事实上,除非左侧操作数为真,否则右侧操作数不会被求值,这意味着它必须从左到右进行求值...但事实上, 所有操作符都是如此。来自 JLS 15.7 :
The Java programming language guarantees that the operands of operators appear to be evaluated in a specific evaluation order, namely, from left to right.
对于方法(和构造函数)参数也是如此。例如,来自第 15.12.4.2 节(评估参数,方法调用的运行时评估的一部分):
The argument expressions, if any, are evaluated in order, from left to right. If the evaluation of any argument expression completes abruptly, then no part of any argument expression to its right appears to have been evaluated, and the method invocation completes abruptly for the same reason.
(值得注意的是这里的“似乎” - JVM 实际上可以无序地评估它们,只要这是不可观察到的......)
关于java - 所有评估都是从左到右进行的吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17054737/