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

Leave a Reply

Your email address will not be published. Required fields are marked *

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <s> <strike> <strong>

Pin It on Pinterest

Share This

Share this post with your friends!

Share This

Share this post with your friends!