Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

java: boolean instanceOf Boolean?

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"
like image 244
epegzz Avatar asked Aug 30 '10 13:08

epegzz


People also ask

Is boolean Instanceof boolean?

Note a boolean is NEVER an instance of Boolean.

Is true Instanceof boolean Java?

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 .

How do you create an instance of a boolean in Java?

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.

What is the alternative to Instanceof in Java?

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.


1 Answers

Because primitive 'true' will be Autoboxed to Boolean and which is a Object.

like image 150
jmj Avatar answered Oct 04 '22 11:10

jmj