java: boolean instanceOf Boolean?

epegzz picture epegzz · Aug 30, 2010 · Viewed 20.2k times · Source

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"

Answer

jmj picture jmj · Aug 30, 2010

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