3

I have

Boolean condition;

public Boolean isCondition() { return condition; }

Is the following usage of this method then allowed, as with a primitive,

if (isCondition())
{
  //...
}

I would use that for primitives but not sure about the class. Does it need to be checked for NULLs? Do I need to getBooleanValue() first?

gene b.
  • 10,512
  • 21
  • 115
  • 227
  • You can do this, but as You sad you have to check for null. Better use simple type. – Rene M. Jul 10 '15 at 19:05
  • Since `Boolean` is a class, it can be null. You can return a `boolean`, since it will be [autoboxed](https://docs.oracle.com/javase/tutorial/java/data/autoboxing.html). – Turing85 Jul 10 '15 at 19:06
  • Thanks Turing85. You probably meant, you can return a Boolean (capital-B), because it will be autoboxed to a boolean (lower-case). – gene b. Jul 10 '15 at 19:07
  • See http://stackoverflow.com/questions/11005286/check-if-null-boolean-is-true-results-in-exception – Kevin Hooke Jul 10 '15 at 19:07

3 Answers3

7

Yes, you can use any boxed primitive (in your case, Boolean) as a primitive itself; namely, your example would work if you could guarantee that condition was set to a non-null value.

The caveat here is that if any of the boxed primitives themselves are null, you will get a NullPointerException when unboxing them. If you have the possibility of that value being null, you should re-evaluate why you're using the boxed primitive in the first place. It may be better to use the unboxed primitive (in your case, boolean) instead.

Makoto
  • 104,088
  • 27
  • 192
  • 230
2

Yes it needs to be checked against null since it is a reference type. The automatic unboxing to the primitive type boolean, which is done in the if condition, relies on calling Boolean#booleanValue() which would throw a NPE in case the condition variable is null.

M A
  • 71,713
  • 13
  • 134
  • 174
0

I found a simple solution,

if(Boolean.TRUE.equals(isCondition()) ){ .. }

This will never throw an NPE because the expression is on the right-hand side, and we can still compare it.

gene b.
  • 10,512
  • 21
  • 115
  • 227