Static and Non-Static Blocks
Use of static blocks:
In real time scenarios, static blocks are used to provide information regarding the project before actual project is executed.
Use of non-static blocks:
If we have many constructors in a class and if every constructor has some common statements, then instead of repeating those statements in each constructor, we place those statements in a non- static block. In this way we can avoid duplication of the code.
Example of program:
System. Out. Prinln (“inside the constructors “);
System. Out. Prinln (“inside the static block “);
System. Out. Prinln (“inside the non- static block “);
Public static void main (string args [ ])
System. Out. Prinln (“inside the main “);
Bdemo1 b1 = new Bdemo1 ();
Inside the static block
Inside the main
Inside the non-static block
Inside the constructors.
Explanation for the output of the above program:
- As soon as JVM starts executing the .class file, it first creates context of the class.
- Then all the static members of the class are loaded into the context.
- Now JVM searches for the main method once it finds the main method, it starts executing all the static blocks other than main method. After that it starts executing main method.
- Inside the main method , we are creating object of the class , JVM encounters the new operator, it reserves memory space in the RAM, i.e. creates the object, loads all the non- static members of the class into the object, initializes the uninitialized variables and then it loads the constructor.
- But after the creation of the object and before the loading of the constructor, it searches for non- static blocks. At this point of time, it executes all the non-static blocks and then loads and executes the constructor.