views:

202

answers:

6

Hi All,

I was doing one of these online Java tests and I was asked this question:

Q: Indicate correct assignment:

Long l = 1; 
Double d = 1;
Integer i = 1;
String s = 1;
Object o = "1";
System.out.println(o);
o = 1;
System.out.println(o);

Please try it yourself before you go any further.

Well I can tell you I got it wrong, I investigated it and found:

//Long l = 1; //cannot widen and then box
Long ll = 1L;//no need to widen, just box
//Double d = 1;//cannot widen and then box
Double dd = 1d;//no need to widen, just box
Integer i = 1;//no need to widen, just box
//String s = 1;//cannot do implicit casting here

Object o = "1";//this compiles and is just plain weird 
System.out.println(o);//output is 1
o = 1;//this also compiles and is also weird 
System.out.println(o);//output is 1

Can someone tell why:

Object o = 1; and Object o = "1";

compile and output 1 in both cases, this is puzzling me.

Many thanks

A: 

Isn't 0=1 an Integer, while o="1" is a String?

Hans Kesting
+6  A: 

"1" is an instance of String class, and String is a subclass of Object class in Java (as any other class). 1 is boxed into an Integer, which is also derived from Object.

Alex B
Wow, thanks for the answer, but I have to tell you I feel so stupid now I should know this.
Ramo
@Ramo: to not question something you don't know would be stupid :-)
Grundlefleck
+1  A: 

Well, the first case "1" is a String literal, so a subclass of object, hence assignable to it. As a string, it output of 1 is relatively simple.

In the second case, auto-boxing is occurring. Integer is a subclass of object, hence assignable to it. Similarly, the output of 1 then makes perfect sense.

developmentalinsanity
+1  A: 

This is because o is of type Object. Every object, in java, extends the class Object. So... when you say Object o = 1, it converts 1 to from int to Integer, which is an Object. Similarly, "1" is a String which is an Object. In both cases, calling System.out.println on an Object invokes the Objects toString method. In both cases, it will print 1.

Tom
+3  A: 

You can put Object o = anything; where anything is any object because all classes derive from the Object class. It works with primitives because of autoboxing feature which came in java 1.5.

fastcodejava
+2  A: 

Because "1" is an instance of a String, and since 1.5 1 is auto-boxable to an Integer; both types are subtypes of Object. Before autoboxing was introduced, Object o = 1; would not compile.

To get the most out of this learning experience, you should be aware of Object's getClass() method. By adding System.out.println(o.getClass().getName()), you can also print the name of the class that the object referred to by o belongs to. In your case, they are java.lang.String (for (Object) "1") and java.lang.Integer (for (Object) 1).

Just for completion, I should mention that you can now also do Object o = false;.

polygenelubricants