Is memory allocated for unused fields in Java?
I'm wondering how the memory allocation works in Java.
I have a class Duck
with two instance variables int size
and String name
. These variables are initialised. Does the memory f开发者_如何学编程or these variables get allocated on the heap during run time, if I'm not instantiating this class?
Thanks, Gene
Several possible scenarios:
If you are not using a class, then the class itself is not loaded in a class loader at all.
If you are using a class, but not instantiating it, then instance variables are not occupying memory since there is no instance to begin with.
If you are using a class, and using an object which is instance of that class, then instance variables are using up memory for each instance, regardless of whether you use these values or not.
IF you are not referencing the class Duck
at all the class isn't even loaded via classloader so the answer is no.
精彩评论