简体   繁体   中英

is parameter of main method eligible for garbage collection?

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?

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.

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.

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM