This example shows how to use the static initializer in Java. The following are the few features of static blocks.
- Static initializers are block of code with static keyword. These are executed when the class is loaded or accessed first time by any application.
- Only static variables can be initialized inside static blocks. Instance variables are not allowed inside static blocks.
- Any number of static blocks can be defined, that will be executed in the order of definition.
- Static methods can be called from the static initializers.
- Static blocks are used for initializing the static or class level variables.
Lets look at the simple example snippet shows how to use the static initializer.
JavaStaticInitializerExample.java
package javabeat.net.core; /** * Java Static Initializer Example * * @author Krishna * */ public class JavaStaticInitializerExample { //Instance variable int i = 0; //Static variable static int j =0; static{ System.out.println("Static Initializer 1 Called"); //i = 0; - instance variable can not be initialized j = 10; //Initialize static variable testMethod();//Can invoke static method, not instance methods } static{ System.out.println("Static Initializer 2 Called"); } //Static method public static void testMethod(){ System.out.println("Static 'testMethod()' called"); } public static void main(String[] args) { System.out.println(j); } }
Output…
Static Initializer 1 Called Static 'testMethod()' called Static Initializer 2 Called 10