Search code examples
javastaticmemory-managementfinal

Java: Memory usage of the final keyword?


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!


Solution

  • 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.