Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Static Method Memory Allocation

We have two classifications heap and stack . When a object is created, memory for object is stored in heap. What if the class has static methods ,which can be called using class name. If object is not created then how will it allocate memory and if it does where will it allocate memory?

like image 691
Harini Avatar asked Oct 06 '11 11:10

Harini


People also ask

Do static methods take memory?

So, if you are using 100 static methods in your program, when the program starts all methods are loaded into memory and will fill the memory unnecessarily. Furthermore static methods increase the risk of memory leaks.

Which type of memory is static method?

There are two types of memory pools namely the stack memory and the heap memory. The main difference between stack memory and the heap memory is that the stack is used to store only the small datatypes whereas heap stores all the instances of the class.

How is memory allocated for static members?

Static variable's memory is allocated at the start of the program, in regular memory, instead of the stack (memory set aside specifically for the program). the advantage of this is that it makes your variable or procedure totally constant, and you can't accidentally change the value.

Do static methods use less memory?

In the static method, less memory is used for execution because memory allocation happens only once because the static keyword fixed a particular memory for that method in ram.


1 Answers

It depends on the JVM, but static fields are usually stored in a special object on the heap. (You can see it in a heap dump) When the ClassLoader is unloaded, its classes and their static "objects"/fields are also cleaned up.

The only thing different about the static "object" is you can't get a reference to it. (But you can use reflection to access the fields)

like image 50
Peter Lawrey Avatar answered Oct 21 '22 17:10

Peter Lawrey