Win a copy of Functional Reactive Programming this week in the Other Languages forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

new object in method

 
Chris Palau
Greenhorn
Posts: 4
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hello,

I am reading the SCJP 6.0 Certification book from Kerry and Kathy and I have a doubt I can't clarify with the book info. I googled but I didn't found any info about that. My question is about the JVM garbage collector.

For example, if I have a method like this:

public void getData() {

StringBuilder sb = new StringBuilder();

}

The book explains this: "local variables are in the stack and instance variables / objects in the heap. When a method finalizes and returns: local variables are eligible for garbage collection", but my question is: what about the object instantiated in the method ? Is automatically eligible for garbage collection also ?

if I have the same example but in a for statement like this:

for (int i=0; i <1000; i++) {
StringBuilder sb = new StringBuilder();
}

StringBuilder object is elegible for garbage collection when the for loop finish ?

Thanks
Chris
 
Omar Al Kababji
Ranch Hand
Posts: 357
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Yes
 
Nitesh Kant
Bartender
Posts: 1638
IntelliJ IDE Java MySQL Database
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Not a performance question. Moving to SCJP certification forum.
Please CarefullyChooseOneForum while posting.
 
Rajshekhar Paul
Ranch Hand
Posts: 140
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Objects created with local variables are always eligible for garbage collection unless the reference to that object is passed outside the scope of that variable.


In the above case, the scope of s is the method body only. But as this method returns the object reference in a return statement, the object will not eligible for
GC after the execution comes out of the method body.


But in the above code, the object refernced by s will be eligible for GC once the execution comes out of the method body as this object is not referenced furthur.

Hope this helps.
 
RaviNada Kiran
Ranch Hand
Posts: 528
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Thank You Very Much Rajsekhar it is really valuable for me
 
Abhi vijay
Ranch Hand
Posts: 509
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I had seen a question in Devaks's Simulator. dont remember the number.

It was adding an object into a collection(Vector), so its not eleigible for GC. But what if this collection is declared inside a method?
 
Punit Singh
Ranch Hand
Posts: 952
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
then collection object itself is eligible for gc after the end of that method.
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic