Class Loading and Static Blocks Execution Using Static Modifier in Java
Static is a keyword which when attached to the method, variable, Block makes it Class method, class variable, and class Block. You can call a static variable/method using ClassName. JVM executes the static block at “CLASS LOADING TIME”
There is an order in which static block/method/variable gets initialized.
- Static Block
- Static Variable
- Static Method
Static Blocks are called even before the main method which is nothing but a static method i.e. execution point of every class.
Sometimes, it is asked in interviews, to print “HELLO” without printing it inside main method or calling any method from main. Answer is to use Static block as they get initialized before main so you can use them to print anything without having any dependency on main Method in java.
Thread = 3 Thread = 2 Non Static Variable Value=1 Thread = 1 Non Static Variable Value=1 Non Static Variable Value=1
You can use Static Variables to save memory or in an operation where you want all threads to maintain one variable instead of having a different variable for every thread.
Used when methods are more relevant to class than an instance of a class. Math Class in java is a great example in Java. It has all the static Methods which you can call using a class name like max, min, pow as these functions do not require different objects to have different values. You can pass parameters and get answer using className.methodName() .
Used when you want to initialize any data before the execution control goes to other methods like the main method.
- Static Methods can only call other static methods i.e. you can not call a non-static method from a static method like the main method.
- Static block can use the only static variable directly
Singleton Design Pattern is the Most Widely used design pattern where only one instance of the class is created and returned for every instance request of class. The static keyword is used to make object creation only once as static occupy memory only once and hence synchronization is maintained for every call.
Below is the example which clearly displays the order of execution. Static Block is called first even it is written after the main method. It proves Static Blocks are the first thing to get called even before the main method.
Static Block Static Variable=3 Static Method
Real-Life Example: To append output to the same log file, one logger object is created, and using logger.info() data can be appended in order of insertion.
Attention reader! Don’t stop learning now. Get hold of all the important Java Foundation and Collections concepts with the Fundamentals of Java and Java Collections Course at a student-friendly price and become industry ready. To complete your preparation from learning a language to DS Algo and many more, please refer Complete Interview Preparation Course.