Java Boolean class variable used in comparison

I have

Boolean condition;

public Boolean isCondition() { return condition; }

      

Is the following use of this method used, as with primitive,

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

      

I would use this for primitives, but not sure about the class. Do I need to check for NULL? Do I need getBooleanValue () first?

+3


source to share


3 answers


Yes, you can use any boxed primitive (in your case Boolean

) as the primitive itself; namely your example would work if you could guarantee that it condition

was set to a non-zero value.



Here caution is that if any of themselves boxed primitives null

, you'll getNullPointerException

when unpacking. If you are in a position to have this value null

, you must reevaluate why you are using the boxed primitive in the first place. It might be better to use the unboxed primitive (in your case Boolean

).

+7


source


Yes, it needs to be checked against null

, since it is a reference type. Automatic unboxing to a primitive type boolean

performed in if

depends on the call Boolean#booleanValue()

that throws NPE in case the variable condition

is equal null

.



+2


source


I found a simple solution,

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

      

This will never call NPE because the expression is on the right side and we can still compare it.

0


source







All Articles