The static keyword in java is used for memory management family. We can apply java static keyword with variables, method, block and nested class. The static keyword belongs to the class.
The static members can beStatic members are identified and get memory location at the time of class loading by JVM in method area.
When variable is declared as static and it is created a single copy of variable and shared all objects at class level. Static variables are essentially global variables. All instances of the class share the same static variable. We can create static variables at class-level only.
Static block is a class level block which is nameless block and contains only static data. If we need to do computation in order to initialize static variables so we can declare a static block that gets executed exactly once, when the class is first loaded.
Need of static block: Static block is used to execute logic at the time of class loading
When a method is declared with the static keyword, it is known as static method. JVM does not execute static method it self. It is executed only if they called explicitly from main(), static variable or static block. Static method’s logic is stored in method area and that logic is executed in java stack area.
The most common example of a static method is main( ) method. Main method is public because it must be called from outside our package. We can call main method explicitly.
Program to execute of static blocks, variables, method and main methodclass StaticKeyword { // static variable static int num = staticMethod(); // static block static { System.out.println("Inside static block"); } // static method static int staticMethod() { System.out.println("from staticMethod "); return 40; } // static main method public static void main(String[] args) { System.out.println("Value of num : "+num); System.out.println("from main"); } }Output
from staticMethod Inside static block Value of num : 40 from main