Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

java.lang.Object o = 1;//why does this compile?

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

like image 683
Ramo Avatar asked Feb 27 '10 08:02

Ramo


People also ask

What is object o Java?

The search(Object o) method is used to return the 1-based position where an object is on this stack.

How do I fix Java Lang UnsupportedClassVersionError error?

In order to overcome the UnsupportedClassVersionError, we can either compile our code for an earlier version of Java or run our code on a newer Java version.

What is object Lang?

Object class is the root of the class hierarchy. Every class has Object as a superclass. All objects, including arrays, implement the methods of this class.


1 Answers

"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.

like image 169
Alex B Avatar answered Oct 25 '22 07:10

Alex B