Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

java Parse Boolean that may be null to Boolean

Tags:

java

boolean

I noticed an issue with java.lang.Boolean class that it can not parse nulls. I know it has the parseBoolean static method but as it's signature states it only accepts String and not an Object.

In other words, it has the following signature:

public static boolean parseBoolean(String s)

but not:

Boolean.parseBoolean(Object)

What is the best way to check a Boolean value without falling on NullPointerException?

like image 613
Yuval Zilberstein Avatar asked Jul 13 '26 03:07

Yuval Zilberstein


2 Answers

Try that approach:

Boolean.TRUE.equals(yourObj);
like image 107
Radoslav Ivanov Avatar answered Jul 14 '26 17:07

Radoslav Ivanov


If you want your parse to return true, false or null as a Boolean object, take a look at Apache Commons Lang. BooleanUtils has a one liner that does exactly this.

https://commons.apache.org/proper/commons-lang/javadocs/api-2.4/org/apache/commons/lang/BooleanUtils.html#toBooleanObject(java.lang.String)

BooleanUtils.toBooleanObject(null) == null
BooleanUtils.toBooleanObject("true") == true
BooleanUtils.toBooleanObject("false") == false
BooleanUtils.toBooleanObject("YES") == true
BooleanUtils.toBooleanObject("nO") == false
like image 24
Chet Avatar answered Jul 14 '26 15:07

Chet



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!