带有boolean的java.lang.NullPointerException [英] java.lang.NullPointerException with boolean
问题描述
我根据另一个问题编写了一个简单的简单代码,这里是:
I wrote a realy simple code based on another question and here it is:
它会抛出一个错误
java.lang.NullPointerException第5行和第17行
java.lang.NullPointerException line 5 and 17
我不知道我在做什么我做错了。
I don't know what I'm doing wrong.
public class Main {
public static String bool(Boolean param){
if(param == true){ (line 5)
return "a";
}else if(param == false){
return "b";
}
return "c";
}
public static void main(String[] args){
System.out.println(bool(true));
System.out.println(bool(null)); (line 17)
System.out.println(bool(false));
}
}
推荐答案
null
无法自动取消装箱到原始布尔值
值,这就是当您尝试将其与 true
进行比较。在
null
cannot be auto-unboxed to a primitive boolean
value, which is what happens when you try to compare it with true
. In
param == true
true
的类型是 boolean
,因此左手操作数也必须是a 布尔值
。您传入 Boolean
,这是一个对象,但可以自动取消装箱到 boolean
。
The type of true
is boolean
, therefore the left-hand operand must also be a boolean
. You are passing in a Boolean
, which is an object, but can be auto-unboxed to boolean
.
因此这相当于
param.booleanValue() == true
显然,如果 param
是 null
,上面抛出 NullPointerException
。
Clearly, if param
is null
, the above throws NullPointerException
.
为了避免隐藏的陷阱自动取消装箱,您可以改为使用布尔
对象:
To avoid the hidden pitfalls of auto-unboxing, you could instead work with the Boolean
objects:
if (Boolean.TRUE.equals(param))
return "a";
if (Boolean.FALSE.equals(param))
return "b";
return "c";
这篇关于带有boolean的java.lang.NullPointerException的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!