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