When you declare a final
variable (constant) in a class, for example:
private static final int MyVar = 255;
How much memory will this require if I have 100,000 instances of the class which declared this?
Will it link the variable to the class and thus have 1*MyVar memory usage (disregarding internal pointers), or will it link to the instance of this variable and create 100,000*MyVar copies of this variable?
Unbelievably fast response! The consensus seems to be that if a variable is both static and final then it will require 1*MyVar. Thanks all!
The final
keyword is irrelevant to the amount of memory used, since it only means that you can't change the value of the variable.
However, since the variable is declared static
, there will be only one such variable that belongs to the class and not to a specific instance.
Taken from here:
If a field is declared
static
, there exists exactly one incarnation of the field, no matter how many instances (possibly zero) of the class may eventually be created. A static field, sometimes called a class variable, is incarnated when the class is initialized . A field that is not declared static (sometimes called a non-static field) is called an instance variable. Whenever a new instance of a class is created, a new variable associated with that instance is created for every instance variable declared in that class or any of its superclasses.
There will be only 1*MyVar memory usage because it is declared as static
.
The static declaration means it will only have one instance for that class and it's subclasses (unless they override MyVar).
An int is a 32-bit signed 2's complement integer primitive, so it takes 4 bytes to hold it, if your example wasn't using static you'd just multiply that by the number of instances you have (for your example of 100,000 instances that's 0.38 of a megabyte - for the field alone, extra overhead for actual classes).
The final modifier on a field means it cannot be repointed to another value (whereas final on a class of method means it cannot be overridden).
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