aspose file tools*
The moose likes Programmer Certification (SCJP/OCPJP) and the fly likes String objects count Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login


Win a copy of Spring in Action this week in the Spring forum!
JavaRanch » Java Forums » Certification » Programmer Certification (SCJP/OCPJP)
Bookmark "String objects count" Watch "String objects count" New topic
Author

String objects count

amarkirt saroay
Ranch Hand

Joined: Mar 16, 2008
Posts: 167
How many String objects are created in the following code:




As per my understanding there will be 5 : "Basic","23","Basic23","Ba23","BA23".
I am not considering s as a seaprate object as its just a eference(we did not do new String() for it)
Is it correct?


SCJP-75%
SCWCD-82%
Milan Sutaria
Ranch Hand

Joined: Jul 10, 2008
Posts: 122
i think you are right as API states "This object (which is already a string!) is itself returned."


SCJP 6 83%
Working on SCWCD/OCPJWCD
Deepak Bajoria
Ranch Hand

Joined: Mar 07, 2008
Posts: 35
before call to substring s="basic23"
s.substring(2,5) returns "sic"


SCJP 5 - 93%
Raphael Rabadan
Ranch Hand

Joined: Jul 05, 2008
Posts: 141
Originally posted by amarkirt saroay:
How many String objects are created in the following code:




As per my understanding there will be 5 : "Basic","23","Basic23","Ba23","BA23".
I am not considering s as a seaprate object as its just a eference(we did not do new String() for it)
Is it correct?


The place where you saw a question like this asked how many string will be created when you invoke a method that executes this code. The answer there is 3. Because before invoking the method there will be 2 strings in the pool already. "Basic" and "23".

Kind Regards,
Raphael Rabadan


SCJP Java 6 (98%) - Story, SCJA (88%) - Story
Milan Sutaria
Ranch Hand

Joined: Jul 10, 2008
Posts: 122
Rapheal, so you intend to say that the two strings "Basic & "23" will be existing much before the method is invoked?? if yes then when are they created?.. as soon as you run the .class file?
Ronald Schild
Ranch Hand

Joined: Jun 09, 2008
Posts: 117
String literals are constants that are created when the class that constains them is loaded. The string objects exist on the heap like any object. They are referenced by the constant pool.

Note that this is only true if no string constant already exists with the same content (if class A causes "Hello" to be created and class B contains "Hello" as well, no new string object with content "Hello" is created if class B is loaded. Instead, both A and B will share).


Java hobbyist.
 
I agree. Here's the link: http://aspose.com/file-tools
 
subject: String objects count