If a object is no more referenced by a live reference then it becomes eligible for garbage collection. See the example below −
public class Tester{ public static void main(String[] args) { test(); } public static void test(){ A a = new A(); } } class A {}
When test() method complete execution, the a object is no more referenced and is eligible for garbage collection. Java garbage collector will deallocate the object when it runs.
To prevent garbage collection, we can create a static reference to an object and then this object will not be garbage collected. See the example below −
public class Tester{ private static A a; public static void main(String[] args){ test(); } public static void test(){ a = new A(); } } class A {}