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
The search(Object o) method is used to return the 1-based position where an object is on this stack.
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.
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"
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With