92

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.

Ravi Gupta
  • 4,468
  • 12
  • 54
  • 85

3 Answers3

152

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?

Jon Skeet
  • 1,421,763
  • 867
  • 9,128
  • 9,194
  • 1
    No its not a Boolean instance but has value as true or false – Ravi Gupta Feb 05 '10 at 10:50
  • 3
    I'm curious about what type is the variable... :) – helios Feb 05 '10 at 10:53
  • 15
    Assuming true / false are Strings you could use: boolean b = Boolean.parseBoolean(String.valueOf(someObject)); Be aware that this will return false for any String value other than "true" (case insensitive) and hence will return false if someObject is null. – Adamski Feb 05 '10 at 10:54
  • 1
    @Jon Answer for the question you asked in last line, We can use `instanceOf` method before casting it to Boolean.This will not give the cast exception. – vikiiii Apr 18 '13 at 16:44
  • @vikiiii: I'm aware of instanceof, but that's a matter of *how* we can check it - that doesn't answer the question I asked, which is the desired *behaviour*. – Jon Skeet Apr 18 '13 at 16:44
  • @Jon If someObject doesn't refer to a Boolean value though, Lets say be a String .Ex: "true" . Then I will like to parse that String as a boolean and I will use parseBoolean method to convert the string to Boolean. Does that answers your question? If not then please answer back and let me know. – vikiiii Apr 18 '13 at 17:04
  • @vikiiii: Well, it answers part of it. It doesn't answer what you'd want to happen if the value actually referred to an Integer though. Or a Button. Or a FileInputStream. And of course I was asking the OP... – Jon Skeet Apr 18 '13 at 17:31
38

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

boolean b = Boolean.valueOf(yourObject.toString())
chburd
  • 4,131
  • 28
  • 33
-2

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
Stephen C
  • 698,415
  • 94
  • 811
  • 1,216
  • Yes. But this is not doing what the OP asked. 1) `int` is not an object type, and certainly not an *arbitrary* object type, 2) this is not a cast. The real problem is that the original question didn't make sense, and the OP never bothered to clarify it. – Stephen C Nov 27 '21 at 03:36
  • not the real issue – mannuk Jul 18 '22 at 21:27