My Question is if the compiler creates "abc" and "def" string in the pool? If yes. What's the benefits of StringBuffer? It also leaves a lot abandoned String objects in the memory.
The following the explaination from another part of book SCJP.Sun.Certified.Programmer.for.Java.5.Study.Guide.Exam.310-055.Dec.2005
String s1 = "spring "; String s2 = s1 + "summer "; s1.concat("fall ") ; s2.concat(s1); s1 += "winter "; System.out.println(s1 + " " + s2); What is the output? For extra credit, how many String objects and how many reference variables were created prior to the println statement? Answer: The result of this code fragment is "spring winter spring summer". There are two reference variables, s1 and s2.
There were a total of eight String objects created as follows: "spring", "summer " (lost), "spring summer", "fall" (lost), "spring fall" (lost), "spring summer spring" (lost), "winter" (lost), "spring winter" (at this point "spring" is lost). Only two of the eight String objects are not lost in this process.
You can always edit your posts. at the top of each you'll see a little paper/pencil icon. this allows you to edit your posts. You can even delete your post there. Note that if yours is the first post of the thread and you delete it, the entire thread goes away.
Thanks for changing your name.
yes, "def" and "abc" will be added to the string pool. EVERY string literal is put in the pool, and you don't have control over this.
Using a StringBuffer actually causes FEWER strings to be abandoned in the heap. A String is immutable. Once it is created, it can never be changed. so when you concatenate Strings, new Strings are created all over the place. each time you use the "+" operator, it's a new String, so
stringone + stringtwo + stringthree + string4;
creates (i believe) 3 strings - two temporary ones that are lost almost as soon as they are created, and one we keep. That is in addition to the four strings we have already created.
The code s1 += "winter" doesn't change the String s1 points to, but creates a brand new string and re-assigns the reference to that new string.
a StringBuffer would change the underlying object itself, thus not causing the object to be lost. [ March 23, 2007: Message edited by: Fred Rosenberger ]
Joined: Mar 16, 2007
Thank you Fred for you reply and I deleted my duplicated post.
Is there anyway that we can see how many String objects are created in the memory? So that I can see what's happening in my JVM.
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