Java中的布尔表达式评估顺序? [英] Boolean expression order of evaluation in Java?

查看:336
本文介绍了Java中的布尔表达式评估顺序?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

假设我有以下表达式

String myString = getStringFromSomeExternalSource();
if (myString != null && myString.trim().length() != 0) {
...
}

Eclipse警告我,在布尔表达式的第二个短语中, myString 可能为空。但是,我知道有些编译器会在第一个条件失败时完全退出布尔表达式。这对Java来说是真的吗?或者评估的顺序是否无法保证?

Eclipse warns me that myString might be null in the second phrase of the boolean expression. However, I know some that some compilers will exit the boolean expression entirely if the first condition fails. Is this true with Java? Or is the order of evaluation not guaranteed?

推荐答案


但是,我知道有些编译器会如果第一个条件失败,则完全退出布尔表达式。这对Java来说是真的吗?

However, I know some that some compilers will exit the boolean expression entirely if the first condition fails. Is this true with Java?

是的,这被称为短路评估。操作员如&& || 是执行此类操作的运营商。

Yes, that is known as Short-Circuit evaluation.Operators like && and || are operators that perform such operations.


或者评估顺序不保证?

Or is the order of evaluation not guaranteed?

不,评估顺序是保证的(从左到右)

No,the order of evaluation is guaranteed(from left to right)

这篇关于Java中的布尔表达式评估顺序?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆