您的位置:首页 > 编程语言 > Java开发

java中&& 、|| 操作的捷径

2016-03-03 11:44 387 查看
String[] t = null;
if (t != null && t.length > 0) {

}一开始的疑问是,如果t为null,再执行t.length,是否会出现Attempt to get length of null array的情况呢?
查阅了文档后,看到:
From the Java Tutorials on operators:

The && and || operators perform Conditional-AND and Conditional-OR operations on two boolean expressions. These operators exhibit "short-circuiting" behavior, which means that the second operand is evaluated only if needed.

也就是说,对于&&、||操作,如果第一个条件,就可以判断组合条件是true 还是false 的话,那么就 不会再对第二个条件进行判断。也就是说,先判断是否为null,再求其lenhth的操作是没有问题的。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: