The docs pretty much answer it: no. It'll return a Boolean
representing a true or false.
public static Boolean valueOf(String s) {
return toBoolean(s) ? TRUE : FALSE;
}
题
Can Boolean.valueOf(String)
ever return null? From what I can see in the java docs, the docs only specify when it returns true. Is false always returned otherwise, or can null be returned? I have not been able to get it to return null in the tests I have done, but I would like to be sure.
Essentially, I want to know if the following code is safe from a NullPointerException:
boolean b = Boolean.valueOf(...);
解决方案
The docs pretty much answer it: no. It'll return a Boolean
representing a true or false.
public static Boolean valueOf(String s) {
return toBoolean(s) ? TRUE : FALSE;
}
其他提示
No, this is impossible. See the source code of the class Boolean
:
public static Boolean valueOf(String s) {
return toBoolean(s) ? TRUE : FALSE;
}
.. and then:
private static boolean toBoolean(String name) {
return ((name != null) && name.equalsIgnoreCase("true"));
}
Actually it could cause NPE but can not return null. Try this:
Boolean bNull = null;
System.print(Boolean.valueOf(bNull)); // -> NPE!
This happens cuz Boolean.valueOf()
accepts String
or boolean
values. Since bNull
is of type Boolean
java tries to unbox bNull
value to pass it as boolean
which causes NPE. Its funny but stupid actually... Also there is no Boolean.valueOf()
for Number
.
No it will not. If null is placed within the argument or if a string is set to null it will return a boolean value of false. You can see expected inputs and outputs in the Java docs: http://docs.oracle.com/javase/7/docs/api/java/lang/Boolean.html#booleanValue()