Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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!

like image 838
Detritus Avatar asked Apr 11 '11 12:04

Detritus


3 Answers

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.

like image 77
Amir Rachum Avatar answered Oct 18 '22 04:10

Amir Rachum


There will be only 1*MyVar memory usage because it is declared as static.

like image 21
wesoly Avatar answered Oct 18 '22 04:10

wesoly


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

like image 4
earcam Avatar answered Oct 18 '22 03:10

earcam