Assigning a number to an Object... Strangely, but this piece of code runs in Java -


assigning number object... strangely, piece of code runs in java:

object a="123abc"; system.out.println("a="+a);   object b=123; system.out.println("b="+b); 

the result being:

a=123abc   b=123 

could please explain why , how works?

i want expand on @juned's answer, based on @art's comment "it's still not obvious me. b's type still - object, right?"

in code:

object = "123abc"; system.out.println("a=" + a);  object b = 123; system.out.println("b=" + b); 

123abc object of class string — string happens defined constant value @ compile time.

a variable reference object of class object or any compatible sub-class.

it similar doing this:

object a; string s = new string("123abc"); // redundant way make string = s; 

the variable string s can assigned variable object a because string is-a subclass of object; object a can reference any kind of object including subclasses.

the same applies object b except 123 primitive integer constant. when assigning object, auto-boxed juned mentioned, doing object b = new integer(123);

again, integer subclass of object, assignment legal.


Comments

Popular posts from this blog

OpenCV OpenCL: Convert Mat to Bitmap in JNI Layer for Android -

android - org.xmlpull.v1.XmlPullParserException: expected: START_TAG {http://schemas.xmlsoap.org/soap/envelope/}Envelope -

python - How to remove the Xframe Options header in django? -