How many objects are eligible for garbage collection once execution has reached the line labeled Line A? String name; String newName = "Nick"; newName = "Jason"; name = "Frieda"; String newestName = name; name = null; //Line A Since string literals in string pool will not be collected, the answer should be 0 right?
Originally posted by Sam Cooper: "Since string literals in string pool will not be collected, the answer should be 0 right?" Holmes, Could you please elaborate your explanation. Thanks
When you declare a String literal in your program, such as "Hello", or "World", these String objects are not created the way any other object is created. Rather, since Strings are immutable, the JVM takes advantage of that and optimizes the creation of Strings. The String literals are created in what is known as the "string pool." Then, if, anywhere throughout your application, you declare another String literal just as you used it before, no new objects will be created, you'll just be reusing the one from the string pool. Because of this special way that String literals are created and handled, string literals are not generally garbage collected. In the case that memory becomes very tight, the literals will be garbage collected, but they do not become "eligible" like all other Java Objects. Had the code looked like this:
Then, after line A was executed, 2 objects would be available for garbage collection (the String objects representing "Bob" and "Tessa"). When you use the new operator for a String, they are created like any other Java object. Only when you use a string literal (as in the initial example), are Strings created in the string pool. I hope that helps. Corey
So, would it make sense to always use constructors when creating String objects to allow for proper garbage collection? Can this be considered a valid optimization? [ February 21, 2002: Message edited by: Ricardo Cortes ]
Sun Certified J2EE Architect for the J2EE Platform (Part 1)<br />Sun Certified Web Component Developer for the J2EE Platform<br />Sun Certified Programmer for the Java 2 Platform
Joined: Aug 26, 2001
Ricardo, Basically, it depends on what you are actually looking for, performance or memory footprint. Creating an object is an expensive operation. I'd say that using String literals (that is strings not created with "new") is a good choice when you know that your strings are not gonna change and that you are gonna use them at several places within your application. Everytime you need to change a String, a new one has to be created and sometimes the performance decreases. StringBuffer is a good option when dealing with strings that are changing over time. If you want to get more information about performance, consider reading the following link: Java Performance Tuning.