• Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

How many Objects are garbage collected?

 
Thomas Markl
Ranch Hand
Posts: 192
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
String s1=new String(" 5 + 5 = 10 ");
s1.trim();
s1.replace('+', '-');
How many objects are created and g.c'd?
I think because of String immutablility the
string object s1 is not changed but for each
operation a new String object is temporarily created.
So I think 3 objects are created and g.c'd.
Ok?
 
Jon Strayer
Ranch Hand
Posts: 133
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Originally posted by Thomas Markl:
String s1=new String(" 5 + 5 = 10 ");
s1.trim();
s1.replace('+', '-');
How many objects are created and g.c'd?
I think because of String immutablility the
string object s1 is not changed but for each
operation a new String object is temporarily created.
So I think 3 objects are created and g.c'd.
Ok?


I get 4. I believe the string constant " 5 + 5 = 10 " is made into a String object before it is passed to the constructor.
 
Jamie Robertson
Ranch Hand
Posts: 1879
MySQL Database Suse
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I wouldn't think this is always the case. I would think String pools may skew that result ( if the methods trim() and replace() can return Strings from the String pool ).
Consider:

If the trim() and replace() methods return Strings from the String pool, then it could possibly only have ever created one String("5 + 5 = 10") for the duration of the program. So only one String may be gc'd in your program, depending on the values of the String. If you don't know about String pools, then you can search the forums, or the net or maybe someone else will take the time to explain. Anyways, your answer may, or may not be right for Strings objects. Also, there are more objects used underneath the covers that may also need to be gc'd, like the underlying char[]'s and whatever other objects are used under the covers.
Jamie
 
Ilja Preuss
author
Sheriff
Posts: 14112
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
The String literal used in the constructor will be part of the constant String pool and therefore never be gc'ed.
The trim and replace methods certainly will create new Strings, as searching for equal Strings in the constant pool (ala intern()) just is to costly do be a reasonable thing to do.
Jamie is right, though, that there probably other objects are created and gc'ed under the hood. So without intimate detail on the implementation, you simply can't give a reasonable answer. (You could even argue that none of the objects might get gc'ed, as the program might terminate beforehand...)
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic