|
String objects are created in two ways, using the new keyword (like all other objects) or by placing the string contents in pair of double quotes, in which case they are called string literals. String objects created by the first way are created on heap and the string literals are created on special area on heap called a (runtime constants) pool. The unique feature of string literals is that identical string literals (that is, literals that contain the same sequence of characters) always refer to the same instance of class String. The following code has three String references, and while it may look like it creates three string objects, when this code executes, at most one string object will be created.
4. String message1 = “Hello World”; // String object is created
5. String message2 = “Hello World”;
6. String message3 = “Hello World”;
7. message1 = null;
When this code runs, JVM checks if there is already a string literal “Hello World” present on pool. If not, a String object is created and message1 refers to it. When line 5 and 6 are executed, the string literal “Hello World” is already on the pool, so message2 and message3 will simply point to it. When the message1 becomes null at line 7, there are still two references, message2 and message3 for the String object created on line 4. Therefore this string literal will not eligible for garbage collection even after line 7.
|
|
The String literals in some implementations of JVM may never be garbage collected. However this is an implementation dependent fact. The exam will not contain questions that rely on specific implementations of JVM. So for the exam, just remember that when all the object references are set to null, then the object becomes eligible for garbage collection. But we cannot say surely whether or not it will be garbage collected. |