Page 1 of 1

About Question enthuware.ocajp.i.v8.2.924 :

Posted: Tue Feb 07, 2017 12:59 pm
by jamesmccreary
Hi Paul,

I had some some research on this but I could not determine if a string literal (i.e. without the

Code: Select all

new String("hello")
part can be autoboxed into a "String" object.

I thought this was the case, but whenever a literal is created, it is created from the string pool. If this is the case, then was indeed a string literal "autoboxed" into a String object (and then widened to type Object)?

Let me know if my question does not make sense, thank you!

Sincerely,
James

Re: About Question enthuware.ocajp.i.v8.2.924 :

Posted: Tue Feb 07, 2017 9:17 pm
by admin
The concept of auto-boxing applies to primitives (i.e. byte, char, int, long, float, double, and boolean). String is an Object. It is not a primitive. So it has nothing to do with boxing/auto-boxing at all. Whether you get a string from a String literal pool or create a new one using the new operator, you will always get a proper String object. So, "hello" and new String("hello") are both objects of String class.

HTH,
Paul.

Re: About Question enthuware.ocajp.i.v8.2.924 :

Posted: Wed Feb 08, 2017 11:25 am
by jamesmccreary
Oh I see, so the strings in the pool are objects themselves as well, just cached. That is the only difference. Thanks for clearing that up!

Re: About Question enthuware.ocajp.i.v8.2.924 :

Posted: Thu Feb 07, 2019 6:20 pm
by skexsi
The thing that threw me off about this question is that no reference variable was declared to create the (new TestClass) object. Does the object not need to have a reference when created?

Re: About Question enthuware.ocajp.i.v8.2.924 :

Posted: Thu Feb 07, 2019 9:51 pm
by admin
No, explicit reference is not required to create an object. But remember that if the object is not referred to from any active part of the code, it may be garbage collected.