Win a copy of Functional Reactive Programming this week in the Other Languages forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

String objects count

 
amarkirt saroay
Ranch Hand
Posts: 167
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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?
 
Milan Sutaria
Ranch Hand
Posts: 122
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
i think you are right as API states "This object (which is already a string!) is itself returned."
 
Deepak Bajoria
Ranch Hand
Posts: 39
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
before call to substring s="basic23"
s.substring(2,5) returns "sic"
 
Raphael Rabadan
Ranch Hand
Posts: 141
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
 
Milan Sutaria
Ranch Hand
Posts: 122
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Posts: 117
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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).
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic