In a method call, if I create an object during that call. When are those objects garbage collected?
Are they placed on the heap and then garbage collected along w
The fact that the execution of the method has ended and now the object is out of scope is irrelevant.
Garbage collection is an implicit operation of the runtime system running in a separate thread in parallel with your code, implementing a specific garbage collection algorithm.
The garbage collection thread runs at unpredictable times-but very often, every second or so according to java docs and when the memory is almost run out, evaluating which objects are eligible to be garbage collected i.e. there are no references to them from root pointers e.g. static variables.
So every object accessible by a root pointer is marked and then recursively the objects referenced by these objects etc.
This can mean scanning the entire process space. Once done, all the objects not "marked" from previous scan go to the free list (are GC'd).
This is a heavy operation as you can see.
The execution of that method has completed.
So the fact that you are out of the scope of a method you called because it has completed, is irrelevant. It does not mean that the runtime knows at that point that the object is done (since GC is run in parallel).
It is not like in C++ that in the end of the method the programmer would call delete on the object since it is not needed. No "delete" is automatically called at the end of the method in Java.
The GC thread will eventually realize that there are no more references to the object allocated on the heap by the method and CG it.
You can call the GC at any point if you want by:
System.gc();
But the GC will run sooner or later anyway.
One thing to note is as long as there is a reference to a method by a root pointer it can not be GC's.
So if in your method you create via new an object on the heap and you store the reference in a container that is static or return it to the caller, the object outlives the method.