6

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?

Lucky
  • 16,787
  • 19
  • 117
  • 151
Yuval Zilberstein
  • 175
  • 1
  • 4
  • 11
  • 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. – user253751 Jan 20 '16 at 09:05
  • see if [this](http://stackoverflow.com/questions/11185321/when-should-null-values-of-boolean-be-used) helps . – Sabir Khan Jan 20 '16 at 09: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`? – steffen Jan 20 '16 at 09:11
  • How did you fail on NullPointerException? – Leet-Falcon Jan 20 '16 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` – Yuval Zilberstein Jan 21 '16 at 10:18

3 Answers3

12

Try that approach:

Boolean.TRUE.equals(yourObj);
Radoslav Ivanov
  • 970
  • 8
  • 23
  • 1
    OP might want the `null`. The question says into `Boolean` not `boolean`, still useful for others that just need the primitive – StevenWernerCS May 02 '19 at 14:58
7

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
Chet
  • 21,375
  • 10
  • 40
  • 58
-1

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

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

Yuval Zilberstein
  • 175
  • 1
  • 4
  • 11