How to cast Object to boolean?

JavaCastingPrimitive

Java Problem Overview


How can I cast a Java object into a boolean primitive

I tried like below but it doesn't work

boolean di = new Boolean(someObject).booleanValue();

>The constructor Boolean(Object) is undefined

Please advise.

Java Solutions


Solution 1 - Java

If the object is actually a Boolean instance, then just cast it:

boolean di = (Boolean) someObject;

The explicit cast will do the conversion to Boolean, and then there's the auto-unboxing to the primitive value. Or you can do that explicitly:

boolean di = ((Boolean) someObject).booleanValue();

If someObject doesn't refer to a Boolean value though, what do you want the code to do?

Solution 2 - Java

Assuming that yourObject.toString() returns "true" or "false", you can try

boolean b = Boolean.valueOf(yourObject.toString())

Solution 3 - Java

use the conditional operator "?" like this below:

int a = 1;   //in case you want to type 1 or 0 values in the constructor call 
Boolean b;   //class var.
b=(a>0?true:false);   //set it in the constructor body

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionRavi GuptaView Question on Stackoverflow
Solution 1 - JavaJon SkeetView Answer on Stackoverflow
Solution 2 - JavachburdView Answer on Stackoverflow
Solution 3 - Javacarlos oliveiraView Answer on Stackoverflow