Win a copy of Programmer's Guide to Java SE 8 Oracle Certified Associate (OCA) this week in the OCAJP forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Same old garbage collection problem!!!

 
Geeta Gune
Greenhorn
Posts: 17
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator

In the above code how many objects will be created? And how many shall be ready for garbage collection?
Also,i want to know 2 things:
1) Will it make a difference if i initialize the String s variable in the loop?
2) Will it make a difference if instead of the string i define an int?
I am very confused with these basic stuff.
Pls help.
Thanx
Geeta
 
Valentin Crettaz
Gold Digger
Sheriff
Posts: 7610
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Basically, String literals are not garbage collected.
The String referred to by s is created once before the loop. No other object is created after that.
Please refer to the following discussions which handle the same topic:
http://www.coderanch.com/t/239961/java-programmer-SCJP/certification/GC-String-object
http://www.coderanch.com/t/236271/java-programmer-SCJP/certification/String-Pool-Redux
http://www.coderanch.com/t/366619/java/java/sting-pool
[ November 29, 2002: Message edited by: Valentin Crettaz ]
 
Alfred Kemety
Ranch Hand
Posts: 279
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
The code you wrote will have one String object created. IF this code was part of a method, and the method does NOT reference this object to a member variable, then supposedly there is one object elligibel for GC. BUT since this object is a string literal, the GC system doesn't garbage collected for optimization purposes.
If you make the initialization in the loop then there should be more object created with every loop but AGAIN since this is a String literal object, there will NOT be any new objects created because of the compiler optimization. UNLESS you use the new operator, there will not be new objects created during the loop itirations.
You can NOT garbage collect a primitive, GC system only works on objects.
but if you meant to creat an Object other than a String, like Integer object then yes it makes a difference since this time to initialize will use the new operator and will creat an object with each itiration - that's if the initialization is inside the loop -.
String s = "String"; //creats one String object
String s = new String("String"); // creats two String objects
HTH
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic