*
The moose likes Programmer Certification (SCJP/OCPJP) and the fly likes string literal GC Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Certification » Programmer Certification (SCJP/OCPJP)
Bookmark "string literal GC" Watch "string literal GC" New topic
Author

string literal GC

preeti khane
Ranch Hand

Joined: Mar 12, 2003
Posts: 93
Careful about String class instantiation in exam and garbage collection, the String s = "hello"; s = null; is not garbage collected but String s = new String ("hello"); s = null; is garbage collected.
Can somebody explain this? It is kinda conflicting...
Alton Hernandez
Ranch Hand

Joined: May 30, 2003
Posts: 443
>>String s = "hello";
>>s = null;
Java optimizes handling of string literals by implementing them as anonymous objects that can be shared.
Strings that have the same literal contents share the same anonymous object.
Consider this code:

Both of the print statement will print true.
This means that this form of initialization does not create new objects. It only creates a reference that points to an anonymous object that cannot be garbage collected.

>>String s = new String ("hello");
>>s = null;
This form of initialization, however, creates a new String object.
Again, consider this code:

The first print statement will print false.
s2 now points to a newly created object that can be garbage collected.
 
 
subject: string literal GC
 
Similar Threads
When will the object get garbage collected
how many object created ?
About Garbage Collection!!
ask help about gc!!!
Garbage collector