7

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?

5
  • 2
    What are you trying to do? Convert a Boolean (that is either true, false, or null) into a boolean? If so, you'll have to decide whether you want nulls to be true or false. Commented Jan 20, 2016 at 9:05
  • see if this helps . Commented Jan 20, 2016 at 9:08
  • Do you think, parseBoolean(null) is only applicable for parseBoolean(Object)? If not, how do you want your Objects to be parsed to Boolean? Commented Jan 20, 2016 at 9:11
  • How did you fail on NullPointerException? Commented Jan 20, 2016 at 10:21
  • I receive from an object entity a field that mus be Boolean (because it is entity) and null is of course false. So i think the best answer is just to compare it to Boolean.TRUE Commented Jan 21, 2016 at 10:18

3 Answers 3

13

Try that approach:

Boolean.TRUE.equals(yourObj);
Sign up to request clarification or add additional context in comments.

1 Comment

OP might want the null. The question says into Boolean not boolean, still useful for others that just need the primitive
9

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

Comments

-1

You can compare it to Boolean.TRUE or Boolean.FALSE. Example:

if (Boolean.TRUE == Box.modeled()) { //do somthing }

3 Comments

this is actually bad because technically you can create new Boolean objects : Boolean b = new Boolean(true); b != Boolean.TRUE
so ... you answer your own question the very same moment you ask it?
also this does not answer your question

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.