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?
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.
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
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...)
The soul is dyed the color of its thoughts. Think only on those things that are in line with your principles and can bear the light of day. The content of your character is your choice. Day by day, what you do is who you become. Your integrity is your destiny - it is the light that guides your way. - Heraclitus
I’ve looked at a lot of different solutions, and in my humble opinion Aspose is the way to go. Here’s the link: http://aspose.com