1

How many objects are eligible for garbage collection immediately before the end of the main() method?

class Test {
    public static void main(String[] args) {
        String[] stringArray = new String[1];
        int[] intArray = new int[1];
        stringArray = null;
        intArray = null;
    }
}

The answer of the question says "stringArray and intArray eligible for garbage collection" but there is "args" array should be eligible for garbage collection. The answer should be "stringArray, intArray and args" but I am not sure.

Is it args param eligible for garbage collection and can be count in the list?

eham
  • 11
  • 1

3 Answers3

2

The key information is in the question as usual. "Before the end of the main()" - the important part is that you're still inside of the main, args is still in the scope and because of that can't be garbage collected.

Amongalen
  • 3,101
  • 14
  • 20
  • 1
    Scope is a language concept, irrelevant to the runtime. As explained in [Can java finalize an object when it is still in scope?](https://stackoverflow.com/a/24380219/2711488), objects referenced by variable in scope still can get garbage collected when being unused. Whether it may actually happen, is implementation dependent. – Holger Nov 27 '19 at 13:10
0

A correction; stringArray and intArray are reference variables which are stored in Stack not in Heap memory so they are not eligible for garbage collection, instead of the Objects which these reference variables are pointing to will be eligible for the garbage collection.

String[] args won't be garbage collected as long as it's in the function scope once the main(String[] args) gets out from function stack then Array Object to which args was pointing, will be eligible for garbage collection.

Zain Ul Abideen
  • 1,617
  • 1
  • 11
  • 25
  • 1
    Arrays in Java are objects. They'll be stored on the heap in any case. The reference will reside on the function's stack frame in this case. – Prashant Pandey Nov 27 '19 at 10:09
0

Arrays in Java are objects, and they'll reside on the heap segment of the program. As long as main runs, args (that resides in the stack frame) is pointing towards it and hence, it won't be garbage collected. As soon as main exists, its stack frame is popped off. Now, the args array will be GCed.

Prashant Pandey
  • 4,332
  • 3
  • 26
  • 44