Saturday, May 7, 2022

Difference between static initializer block vs instance initializers in Java? Example

In Java, you can initialize member variables or fields in the same line you declare, in the constructor, or inside an initializer block. There are two types of initializer blocks in Java, static initializer block to initialize static variables and instance initializer block to initialize non-static fields. As the name suggests, the main difference is their purpose, instance initializer block if for instance variables, and static initializer block is for static variables. Another key difference between them is the time of execution. 

Static initializer block is executed when class is loaded into memory, while instance initializer block is executed when an instance of the object is created using the new() operator. Let see a couple of more differences between them.


Difference between static initializer block vs. instance block in Java

Here is a couple of important difference between static initializer block and instance initializer block in Java. Along the way, you will also learn how and when to use static initializer blocks in Java applications. 

1. You should only use initializer block either for combining initialization of related variables or if initialization logic is complex like:

static id = 2; // should be done in the same line
               //, no static initializer block

static {

// random id starting form 100

}


2. You can assign values to fields that are not declared yet, but you cannot read their values. The best practice is to avoid that; you should only initialize variables that are declared already

here is a sample code example:

 private static int version = 1;
    private static String codename;
    private static String shortname;
    
    static{
        System.out.println("inside static initializer block");
        codename ="Tiger";
        shortname = "TT";
        subversion = 2; //possible but a bad coding practice
    }
    
    private static int subversion;


3. static initializer block is executed when the class is loaded in memory. In contrast, an instance initializer block is executed when a new class instance is created using a new operator.

Here is an example of an instance initializer block in Java:

    private int count;
    private int groups;
    
    {
        System.out.println("inside instance initializer block in Java");
        count = 2;
        groups = 3;
    }

It's very similar to the static initializer block except for the static keyword.


4. Both static and instance initializer blocks are executed in the order they appear in the source file. 

5. If static initializer blocks throw an exception, then you will get ExectionInitializerError.

6. You can use static initializer block to initialize static variables and instance initializer block to initialize instance variables in Java. 


How to use static initializer block in Java



Java Program to demonstrate static initializer block:

Here is a sample program that demonstrates the use of how to use static initializer block in Java. You can see that the static initializer block is executed before the main method in Java

public class Testing {
    
    private static int version = 1;
    private static String codename;
    private static String shortname;
    
    static{
        System.out.println("inside static initializer block");
        codename ="Tiger";
        shortname = "TT";
        subversion = 2; //possible but a bad coding practice
    }
    
    private static int subversion;
    
    private int count;
    private int groups;
    
    {
        System.out.println("inside instance initializer block in Java");
        count = 2;
        groups = 3;
    }

    public static void main(String args[]){
        System.out.println("Inside main method");
        
        System.out.println("version: " + version);
        System.out.println("codename: " + codename);
        System.out.println("shortname: " + shortname);
        
        Testing t = new Testing();
        
        System.out.println("count instance varaible: " + t.count);
        System.out.println("groups instance varaible: " + t.groups);
    }
}

Output:
inside static initializer block
Inside main method
version: 1
codename: Tiger
shortname: TT
inside instance initializer block in Java
count instance varaible: 2
groups instance varaible: 3


You can see that the static initializer block is executed when the class is loaded in the memory. It's also executed before the main method is called in Java. On the other hand, an instance initializer block is called when a new object is created. 

That's all about the difference between static and instance initializer blocks in Java. It's an important concept for Java programmers to learn, particularly the execution and initialization order that the static initializer block is initialized before the main method is executed.

You can also use this concept to initialize a thread-safe singleton in Java; remember the static holder pattern. This is also an important concept from a Java certification point of view. 

If you are preparing for Java SE 11 certification, you will find a couple of questions on this concept. Even my Java SE 11 certification Practice tests have a few questions to test your knowledge about how Java variables are initialized and how static code blocks are executed. 


Other related Java articles and Tutorials You May Like:

  • Can abstract class have a constructor in Java? (answer)
  • Top 10 Courses to learn Java in-depth (courses)
  • Top 5 Free Java 8 and Java 9 courses for Programmers (courses)
  • 5 Free courses to learn object-oriented programming in Java (courses)
  • 10 Must-Read books to learn Java in-depth (books)
  • Can you run a Java program without the main() method in Java? (answer)
  • Can you overload or override the static method in Java? (answer)
  • My favorite free courses to learn Java (courses)
  • Can we declare a class static in Java? (answer)
  • 10 Advance Java courses for experienced developers( courses)
  • Can you make an array volatile in Java? (answer)
  • 10 Advanced Java books for experienced programmers (books)
  • Can you make an abstract class final in Java? (answer)
  • Can you override a private method in Java? (answer)
  • 50+ Java Interview Questions for beginners (interview questions)


Thanks for reading this article so far. If you find this article useful, then please share it with your friends and colleagues. If you have any questions or feedback, then please drop a note. 

No comments:

Post a Comment

Feel free to comment, ask questions if you have any doubt.