Tuesday, 17 March 2020

The Word Static

Static means the data tied to class, instead of the instance of the object.  With ordinary non-static method, you have to create an instance of the class and use it to access the method. Of course, since static methods does not need an instance to be called, they cannot directly access non-static methods or members. 

Where Does They are stored and what does it actually mean?


Static Variables

When we create a static variable or method it is stored in the special area on heap: PermGen(Permanent Generation), where it lays down with all the data applying to classes(non-instance data). Starting from Java 8 the PermGen became - Metaspace. The difference is that Metaspace is auto-growing space, while PermGen has a fixed Max size, and this space is shared among all of the instances.A static variable is initialised only, when the class is first loaded into the JVM, which happens the first time it is referenced in code, not when the instance is created.

Static Methods

Static methods are stored in Metaspace space of heap as they are associated to the class in which they reside not to the objects of that class. But their local variables and the passed arguments are stored in the stack. Since static methods belong to the class - they can be called without creating a object of the class. The use-case of static methods is the same as with static variable.

Static Block

Static blocks are called when the class is referenced first time in the code. When we have more than one static block then they are executed in sequential execution of the blocks.  

Static class

In Java we can have the class as static, we cannot mark our "top-level" class as static, But... Java allows us to define a class within another class. Such a class is called a Nested class. The class which enclosed nested class is known as Outer class. In Java, we can’t make Top level class static. Only nested classes can be static.

No comments:
Write comments