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 and Garbage Collection

 
Yun Hao
Greenhorn
Posts: 11
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Suppose in the code, we have statement like this:

1. String s1="My String";
2. s1="Another String";

my question is after line 1, whether there is object created? After line 2, whether there is object eligible for garbage collection?
 
Premil Jacob
Ranch Hand
Posts: 30
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
both the strings you created i.e,

1. String s1="My String";
2. s1="Another String";

both the strings "My String" and "Another String" are intern'd. What that means is that both the strings will only garbage collected when the java runtime exits.
 
Yun Hao
Greenhorn
Posts: 11
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Thanks Permil. I want to be much clearer. You are saying that no object is eligible for garbage collection after line 2. Is that what you mean? This is what I thought first. Because "My String" is in the string literal pool.If I change the line 1 to s1=new String("My String"); after line 2, I think one object is eligible for garbage collection.

Thanks
 
Francis Palattao
Ranch Hand
Posts: 91
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
If I change the line 1 to s1=new String("My String"); after line 2, I think one object is eligible for garbage collection.


Yes I agree the "My String" literal is an object created but no reference to it. So it is eligible for garbage collection but I think since it is a literal I heard it will never be garbage collected because there is a reference to it from the string literal pool.
 
It is sorta covered in the JavaRanch Style Guide.
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic