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

来源:互联网 发布:yii2框架源码pdf 编辑:程序博客网 时间:2024/06/05 03:59
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的操作是没有问题的。

0 0
原创粉丝点击