Static Initializer In Java

This example shows how to use the static initializer in Java. The following are the few features of static blocks.

  1. Static initializers are block of code with static keyword. These are executed when the class is loaded or accessed first time by any application.
  2. Only static variables can be initialized inside static blocks. Instance variables are not allowed inside static blocks.
  3. Any number of static blocks can be defined, that will be executed in the order of definition.
  4. Static methods can be called from the static initializers.
  5. 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

Comments

comments

About Krishna Srinivasan

He is Founder and Chief Editor of JavaBeat. He has more than 8+ years of experience on developing Web applications. He writes about Spring, DOJO, JSF, Hibernate and many other emerging technologies in this blog.

Speak Your Mind

*