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.
boolean val = false; To convert it into an object, use the valueOf() method and set the argument as the boolean primitive. Boolean res = Boolean. valueOf(val);
You can use CAST() to convert any integer or floating-point type to BOOLEAN : a value of 0 represents false , and any non-zero value is converted to true . You can cast DECIMAL values to BOOLEAN , with the same treatment of zero and non-zero values as the other numeric types. You cannot cast a BOOLEAN to a DECIMAL .
You cannot cast an integer to boolean in java. int is primitive type which has value within the range -2,147,483,648 to 2,147,483,647 whereas boolean has either true or false. So casting a number to boolean (true or false) doesn't makes sense and is not allowed in java.
Use the valueOf() method to convert boolean value to Boolean. Firstly, let us take a boolean value. boolean val = false; Now, to convert it to Boolean object, use the valueOf() method.
The as operator may only be used with reference types, so it is not possible to do use as to try a safe-cast to bool: // This does not work: "The as operator must be used with a reference type ('bool' is a value type)" object rawValue = map.GetValue (key); bool value = rawValue as bool;
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:
CJ J.: It's worth noting that new Boolean isn't a boolean but rather an instance of Boolean. Primitives are cheaper and should be preferred over the object type. CJ J.: new Boolean (str) returns an object type.
If a new Boolean instance is not required, this method should generally be used in preference to the constructor Boolean (boolean), as this method is likely to yield significantly better space and time performance.
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?
Assuming that yourObject.toString() returns "true" or "false", you can try
boolean b = Boolean.valueOf(yourObject.toString())
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With