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.
The code is also available:
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()
Related
This is a code segment from another StackOverflow question:
#Override
public String convertToDatabaseColumn(final UUID entityValue) {
return ofNullable(entityValue).map(entityUuid -> entityUuid.toString()).orElse(null);
}
I am really struggling to understand the use of the Optional class. Is the return code saying "return the value of the map (a String) or NULL if that fails?
How can return be acting on a method rather than a Class - that is Optional.ofNullable()?
This is a really bad use of Optional. In fact the java developers themself say that optional should not be used in such cases, but only as a return argument from a method. More can be read in this great answer: Is it good practice to use optional as an attribute in a class
The code can be rewritten to this:
#Override
public String convertToDatabaseColumn(final UUID entityValue) {
return entityValue == null ? null : entityValue.toString();
}
Is the return code saying "return the value of the map (a String) or NULL if that fails?
Yes. You can check the documentation of Optional here. It tells you exactly what map and orElse do.
How can return be acting on a method rather than a Class - that is Optional.ofNullable()?
You are not returning the method. You are returning the return value of a method. Look at this simple example:
int myMethod() {
return foo();
}
int foo() { return 10; }
See? I am not returning foo the method, I am returning 10, the return value of foo.
Note that it is possible to return methods, with functional interfaces.
In this case, you are returning the return value of the last method in the method chain, orElse. ofNullable creates an Optional<T>, then map is called on this object and returns a new Optional<T>, then orElse is called and its return value is returned.
Lets go step by step:
ofNullable(entityValue)
creates an Optional of the incoming parameter (which is allowed to be null, using of() a NPE gets thrown for null input)
.map(entityUuid -> entityUuid.toString())
Then you pick the actual value, and invoke toString() on that value ... which only happens if entityValue isn't null. If it is null, the result comes from orElse(null).
In the end, the result of that operation on the Optional is returned as result of the method.
The above code is nothing but a glorified version of
if (entityValue == null) return null;
return entityValue.toString();
Optionals have their place in Java, but your example isn't a good one.
It doesn't help readability a bit, and you are not alone with wondering "what is going on here".
The code can be turn like this :
public String convertToDatabaseColumn(final UUID entityValue) {
if(entityValue==null){
return null;
}else{
return entityValue.toString();
}
}
Your initial code have two statements:
Optional.ofNullable(entityValue): create an Optional Object to say the value can be present or not.
.map(entityUuid -> entityUuid.toString()).orElse(null); you apply some operation to your Optional object, return a string of it or null.
This will avoid a null pointer exception in a more elegant way.
Optional.ofNullable(T value):
Returns an Optional describing the specified value, if non-null, otherwise returns an empty Optional.
Optional.orElse(null)
Return the value if present, otherwise return null.
Follow this link
When I compile my code this way, I get the mentioned error:
public class SymTree{
public static boolean isSym(BT bt)
{
return(IsMirror(bt.left, bt.right));
}
private static boolean IsMirror(BT lr,BT rr)
{
if(lr==rr==null) (((ERROR HERE)))
return true;
.....
However when I compile like this
private static boolean IsMirror(BT lr,BT rr)
{
if(lr==rr)&&(lr==null))
return true;
.......
I get no error. The error is uncomparable types with nulltype and boolean, however non of my compared objects are boolean- they are both objects from a BT(Binary Tree) class, which has been defined elsewhere.
Thank you!
Examine (lr==rr==null). lr==rr is a boolean. It is primitive and can not be compared to null.
The reason it's giving you that error is because when you write this:
if (lr==rr==null)
The compiler interprets it similar to one of the following:
if ((lr==rr) == null)
if (lr == (rr==null))
Basically, you're comparing a boolean condition (either lr==rr or rr==null) to a nullable type, which doesn't make sense since booleans are value types and can never be null.
It is because in if(lr==rr==null), lr==rr is a boolean comparison which you are comparing with a null by doing ==null.
For Example, if suppose lr is equal to rr then lr==rr will return true next you are comparing whether true==null. Here you get error because boolean and null are not comparable.
I'm not talking about checking if a boolean is null as a means to check if it is initialized. Because that won't work. So I thought this might work:
public class MyClass{
private boolean setting;
private boolean getSetting{
// get the setting;
}
public void main{
if (setting != (true && false))
setting = getSetting();
// do main stuff;
}
}
And it does! So my question is: would this be a good practice compared to the alternative, which would be the use of an extra variable:
public class MyClass{
private boolean initialized = false;
private boolean setting;
private boolean getSetting{
// get the setting;
}
public void main{
if (!initialized)
setting = getSetting();
initialized = true;
// do main stuff;
}
}
Booleans are a primitive type, therefore they do not need to be initialized. The default value for a boolean is false.
The first code sample returns false because the phrase true && false will always equate to false (&& checks whether both statements are true, which they aren't, so it is false) and then you check if setting, which is also false, is unequal to that, which it is not. An initialized variable could therefore be useful.
You can read more about defaults and primitive types here.
if (setting != (true && false)) doesn't do what you think it's doing.
The expression (true && false) always evaluates to false: you're doing a logical AND on the literal values true and false.
That means that your test reduces to if (setting != false). Since setting is not initialized, it defaults to false. When the code runs it checks if (false != false), which evaluates to false.
When I run the code you posted it does not call getSetting, as expected.
In your example, best practice would be to initialize the variable inside the constructor:
public class MyClass {
private boolean someSetting;
public MyClass() {
someSetting = getSetting();
}
private boolean getSetting() {
...
}
public void main() {
// By the time this is called we can guarantee that someSetting has been initialized correctly
// Do main stuff...
}
}
The issue with (setting != (true && false)) has already been discussed, but the real issue is that the primitive boolean only has its two obvious options. It's always either true or false. If both of those are meaningful answers, then that value cannot also indicate whether it's been initialized or not. An initialized, meaningful false will look the same as not having been initialized.
The best solution if it's available is, as Cameron Skinner answered above, to ensure the variable is always initialized by doing so either where it's declared or in the constructor. That, however, requires that the answer to what setting should be is known at the time the class is instantiated.
If the proper value is not necessarily known at that point and might need to be set later (so having been deliberately set to false is a different situation than having never been set), then you have a couple options:
One is as shown in the initial post, to have a separate initialized variable telling you whether it's happened or not. That might look a little clunky, but it works.
The other option is to use a Boolean object rather than a boolean primitive for setting. A Boolean object can be set to either true or false, but it initially defaults to null, so you can use a check for null to determine whether it has been set or not.
I am trying for null check like below
if (isTrue == null)
compile error says : "The operator == is undefined for the argument type(s) boolean"
Please help, how to do null check.
Thanks
You can't do null check on primitive types. boolean is a primitive type.
If you absolutely need to represent a null value with a boolean variable, you need to use the wrapper class java.lang.Boolean.
So, your example would be:
Boolean isTrue;
isTrue = null; // valid
isTrue = true; // valid
isTrue = false; // valid
if (isTrue == null) {
// valid!
}
Here's the WIKIPEDIA entry for primitive wrapper classes.
The right way is
boolean isTrue;
if(!isTrue)
or
if(isTrue)
You can not check if the boolean is null or not.boolean must be true or false.
A boolean is a primative type and cannot be null.
A boolean cannot be null in java.
A Boolean, however, can be null.
I am surprised to know that getBoolean() and valueOf() method returns different results for the same input string.
I have tried to pass the "true" to both the methods. But getBoolean() gives me false output whereas valueOf() gives me right output that is true. Why?
The API-documentation is your friend.
Boolean.getBoolean probably doesn't do what you think it does:
Returns true if and only if the system property named by the argument exists and is equal to the string "true".
Boolean.valueOf is probably what you're looking for:
The Boolean returned represents the value true if the string argument is not null and is equal, ignoring case, to the string "true".
The javadoc of getBoolean clearly state that it searches the System Properties. The value that you pass to it is the name of the system property, not a "true" or "false" string.
E.g., `var b = Boolean.getBoolean("some.property");
Boolean.getBoolean must be the worst placed method in java. One of the big WTF.
Why wasn't it placed in System or Properties or whatever?
So to answer your question - yes, it is a very confusing thing and you can just click on the method in your IDE to see the code or read the javadoc.
Here's the source code:
public static boolean getBoolean(String name) {
boolean result = false;
try {
result = toBoolean(System.getProperty(name));
} catch (IllegalArgumentException e) {
} catch (NullPointerException e) {
}
return result;
}
I too found this issue recently when using Boolean.getBoolean() . In addition if you want to have a null check you can use Boolean.parseBoolean which will return false in case of nulls
class Boo1
{
public static void main(String[] args)
{
System.setProperty("true","true");
System.setProperty("false","true");
boolean d=Boolean.getBoolean("true");
System.out.println(d);
}
}