I'm a bit confused: I have a function, that takes an Object as argument. But the compiler does not complain if I just pass a primitive and even recognizes a boolean primitive as Boolean Object. Why is that so?
public String test(Object value)
{
if (! (value instanceof Boolean) ) return "invalid";
if (((Boolean) value).booleanValue() == true ) return "yes";
if (((Boolean) value).booleanValue() == false ) return "no";
return "dunno";
}
String result = test(true); // will result in "yes"
Note a boolean is NEVER an instance of Boolean.
instanceof is a keyword. It checks if an object reference is an instance of a type, and returns a boolean value; The <object-reference> instanceof Object will return true for all non-null object references, since all Java objects are inherited from Object .
Boolean bool = new Boolean("true"); In the same way, “False” value is added. Boolean bool = new Boolean("false"); The following is an example displaying how to create a Boolean object from Boolean value.
The isInstance method is equivalent to instanceof operator. The method is used in case of objects are created at runtime using reflection. General practice says if the type is to be checked at runtime then use the isInstance method otherwise instanceof operator can be used.
Because primitive 'true
' will be Autoboxed to Boolean
and which is a Object
.
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