Static Initializer , Instance Initializer And Constructor In Java

This example show the order of the Java initialization blocks. Java has static initializer, instance initializer and constructor for initializing the variables. These blocks are used for the different purposes and leads to confusion among the programmers.

Order of the execution of these blocks are as follows:

  • All Static Initializers executed in the same order how it is declared
  • All the instance initializers executed in the same same order how it is declared
  • After the above two execution, finally constructor is called.

static/instance initializers can be used to set the value of “final” static/instance variables whereas a constructor cannot.

Anonymous inner classes can’t have a constructor (as they’re anonymous), so they’re a pretty natural fit for instance initializers.

I have written a simple program which demonstrates the order of execution for static initializer, instance initializer and constructor.

JavaInitializationExample.java

package javabeat.net.core;

/**
 * Java Initialization Example
 *
 * @author Krishna
 *
 */
public class JavaInitializationExample {

	//Static variable
	static int j = 0;

	//Instance variable
	int i = 0;

	//Instance Block
	{
		System.out.println("Instance Initializer Called");
		i = 0; // instance variable can be initialized
		j = 10; //Initialize static variable
		instanceMethod();
	}

	//Static block
	static{
		System.out.println("Static Initializer Called");
		testMethod();//Can invoke static method, not instance methods
	}

	//Constructor
	public JavaInitializationExample(){
		System.out.println("Constructor Called");
		j = 20;
	}
	public static void main(String[] args) {
		System.out.println("J Value Before Instance Initializer Called : "+j);
		new JavaInitializationExample();
		System.out.println("J Value After Instance Initializer Called : "+j);
	}

	//Static method
	public static void testMethod(){
		System.out.println("Static 'testMethod()' called");
	}
	//Static method
	public static void instanceMethod(){
		System.out.println("Instance 'instanceMethod()' called");
	}

}

Output…

Static Initializer Called
Static 'testMethod()' called
J Value Before Instance Initializer Called : 0
Instance Initializer Called
Instance 'instanceMethod()' called
Constructor Called
J Value After Instance Initializer Called : 20

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!