Win a copy of Machine Learning Systems: Designs that scale this week in the Scala forum
or Xamarin in Action: Creating native cross-platform mobile apps in the Android forum!
  • Post Reply Bookmark Topic Watch Topic
  • New Topic

String literals & GC  RSS feed

 
Greenhorn
Posts: 20
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Dear ranchers,
Please confirm that String literals are not the subject for GC:
String s = null; //not eligible for GC
String s = new String(null); //eligible for GC
Thnx
 
Enthuware Software Support
Rancher
Posts: 4181
34
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
>String s = null; //not eligible for GC
No. There is nothing available for GC here.
String s = "asdf"; //not eligible for GC
String object refered by s is NOT eligible for GC.
String s = new String("asdf");
String object refered by s (not s itself) is eligible for GC.
HTH,
Paul.

------------------
SCJP2, SCWCD Resources, Free Question A Day, Mock Exam Results and More!
www.jdiscuss.com
Get Certified, Guaranteed!
JQPlus - For SCJP2
JWebPlus - For SCWCD
JDevPlus - For SCJD
 
Ranch Hand
Posts: 317
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
If you use the String constructor " new String()" then it eligible for GC when the reference is set to null. If you do it the other way(String a = "123") it is stored in a pool which is not eligile for GC. This is what i gathered from my understanding.
Good luck
Faisal
 
Ranch Hand
Posts: 2120
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
In this thread there is program that shows how string literals are not made eligable for gc:
http://www.javaranch.com/ubb/Forum24/HTML/012708.html
hope helps
 
Igor Gaschits
Greenhorn
Posts: 20
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Thank you all, for your prompt replies. Jose, your code killed my final doubts about this subject. Once in a while, I find this type of questions in mock exams and always choose "0 obj eligible for GC" and get failure on this question. I also hope, there will be no questions like this on the real test or at least they will accept the right choice.
Thanks again!
 
To avoid criticism do nothing, say nothing, be nothing. -Elbert Hubbard. Please critique this tiny ad:
Rocket Oven Kickstarter - from the trailboss
https://coderanch.com/t/695773/Rocket-Oven-Kickstarter-trailboss
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!