java - 所有评估都是从左到右进行的吗?

标签 java

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/

相关文章:

java - 迭代排序数组以删除重复项

java 对象 - 公共(public)行为与静态行为

java - 关于渲染PDF和修改Uri

java - 是否可以让 MediaPlayer 播放一个音频文件并在播放完后播放下一个?

java - 剥离项目后,tomcat 不会从 Eclipse 中启动

java - 在 java 中使用命令行参数时未获得正确的输出

java - 具有回调授权的 JTwitter OAuth

java - 如何在屏幕上查找 JTree 节点的位置

java - 在 jpa 中使用命名查询更新查询无法正常工作

java - 如何在Spring MVC测试框架中测试配置静态资源