Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Utility method to convert Boolean into boolean and handle null in Java

Is there a utility method in Java which converts Boolean into boolean and automatically handles null reference to Boolean as false?

like image 864
ps-aux Avatar asked Jul 25 '14 07:07

ps-aux


People also ask

How do you handle Boolean null value in Java?

You can use the class Boolean instead if you want to use null values. Boolean is a reference type, that's the reason you can assign null to a Boolean "variable". Example: Boolean testvar = null; if (testvar == null) { ...}

How do you change a Boolean to a Boolean in Java?

Now, to convert it to Boolean object, use the valueOf() method. Boolean res = Boolean. valueOf(val); Let us now see the complete example to convert boolean value to Boolean.

How do you handle Boolean null?

Nullable boolean can be null, or having a value “true” or “false”. Before accessing the value, we should verify if the variable is null or not. This can be done with the classical check : if … else …

How do you convert Boolean to Boolean?

To convert Boolean Primitive to Boolean object, use the valueOf() method in Java.


1 Answers

How about:

boolean x = Boolean.TRUE.equals(value); 

? That's a single expression, which will only evaluate to true if value is non-null and a true-representing Boolean reference.

like image 84
Jon Skeet Avatar answered Sep 19 '22 14:09

Jon Skeet