My AP Computer Science teacher tells me not to use static methods because Java garbage collection only affects non-static methods, and therefore static methods that are no longer used will take up extra memory. I'm almost positive that GC should never affect any methods, only objects, but I wanted to be sure before I say anything. So does GC have anything to do with methods?
use static methods because Java garbage collection only affects non-static methods, and therefore static methods that are no longer used will take up extra memory.
I think you miss understood what he/she said. A method is only unloaded when its ClassLoader is unloaded, in most Java SE programs, that is never.
Assuming she really said methods and not fields then your teacher is wrong on this occasion. As you say, garbage collection is the process of reclaiming memory from objects that have been allocated, the scope of the method that allocated them is irrelevant.
As a side note, static fields are a different matter. Holding objects in a static field (usually) does prevent the garbage collector doing its thing as the class will always hold a reference to it and so it won't be eligible for collection.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With