我想知道如果一个变量为空,并且在 boolean 条件下,对该空变量调用一个方法,会发生什么。会抛出异常吗?
MyObj chair = null
chair = getSpecialMethod();
if(chair != null && chair.size()){
....
}
如果chair
,情况会怎样?为 null 时,即使之前检查了空值,也会抛出异常 chair.size()
被称为?
最佳答案
不,当 chair
为 null
时,条件的第二部分不会被评估,因为第一部分为 false
,因此 >NullPointerException
不会抛出。
来自部分15.23. Conditional-And Operator &&在 Java 语言规范中:
The conditional-and operator && is like & (§15.22.2), but evaluates its right-hand operand only if the value of its left-hand operand is true.
关于Java: boolean 表达式中的短路评估,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17155736/