File APIs for Java Developers
Manipulate DOC, XLS, PPT, PDF and many others from your application.
http://aspose.com/file-tools
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

string literal GC

 
preeti khane
Ranch Hand
Posts: 93
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Posts: 443
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
>>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.
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic