views:

164

answers:

4

Hello everyone.

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"
+14  A: 

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

org.life.java
(+1) And here's some [documentation to go along with it](http://download.oracle.com/javase/1.5.0/docs/guide/language/autoboxing.html)
Tim Stone
Further reading: http://download.oracle.com/javase/1.5.0/docs/guide/language/autoboxing.html@jpegzz, the code would not compile if you ran with 1.4.x
SB
interesting :) Well, the docs suggest only to use autoboxing if really neccessary so I wont. But it's nice to know that this is not a bug but a feature :)
epegzz
A: 

its called autoboxing - new with java 1.5

http://download.oracle.com/javase/1.5.0/docs/guide/language/autoboxing.html

Adam Butler
+2  A: 

This part of the method:

  if (((Boolean) value).booleanValue() == true ) return "yes";
  if (((Boolean) value).booleanValue() == false ) return "no";
  return "dunno";

Could be replaced with

  if (value == null) return "dunno";
  return value ? "yes" : "no";
Paul Tomblin
not the same as OP's code behavior. `null` would return "invalid" since `null` is not an instance of `Boolean` (you're missing that line from OP's code in your first code above); "dunno" would never be returned at all (by original code). Without that line your first code would throw a NPE when value is `null`.
Carlos Heuberger
@Carlos, I can never remember if `instanceof` returns true or false with all nulls, so I usually avoid the case by checking for null beforehand.
Paul Tomblin
+1  A: 

Like previous answers says, it's called autoboxing.

In fact, at compile-time, javac will transform your boolean primitve value into a Boolean object. Notice that typically, reverse transformation may generate very strange NullPointerException due, as an example, to the following code :

boolean b = null;
if(b==true) <<< Exception here !

You can take a look at JDK documentation for more infos.

Riduidel