Originally posted by Pallavi Chakraborty:
I was also wondering if we had the statement
I i1 = new I("A");
in a main method instead of the class J, they would be class instance variables
. How does this affect Garbage collection.
A variable that is declared inside of a method is a method-local variable--it is not an instance variable. An object that is referenced only by a method local reference will be eligible for garbage collection when the method runs to completion. In other words, the object becomes eligible for garbage collection when the reference is no longer in scope.
An object that is created inside of a method might also be referenced outside of the method. In that case, the object would not be eligible for garbage collection as long as the reference remains in scope.