Pages

Footer Pages

Spring Boot

Java String API

Java Conversions

Kotlin Programs

Kotlin Conversions

Java Threads Tutorial

Java 8 Tutorial

Tuesday, April 9, 2019

Static initializers and Initializer blocks in Java

Static initializers in Java

The following are the common interview questions and asked in programming written test.

What is Static initializers ?
What is Static block in Java?
Use of Static block ?
What is Initializer blocks in Java?
When Initializer will be invoked?


Initializer blocks:


Initializer block is a block which is started with "{" and enclosed with "}". We can write these blocks anywhere in the program.





Refer below example and Guess output.
package com.java.w3schools.core.initializer;

/**
 * @author Java-W3schools Blog
 * @File Name InitializerExample.java
 */

public class InitializerExample {
   
    {
        System.out.println("Initilizer block one");
    }

    public static void main(String[] args) {

        System.out.println("Main method");
    }
}

Output:


Main method

We will create now object for InitializerExample class.
package com.java.w3schools.core.initializer;


/**

 * @author Java-W3schools Blog

 * @File Name InitializerExample.java

 */


public class InitializerExample {

    {
        System.out.println("Initilizer block one");
    }

    public static void main(String[] args) {
        InitializerExample exampleOne = new InitializerExample();

        InitializerExample exampleTwo = new InitializerExample();

        System.out.println("Main method");
    }

}

Output:

Initilizer block one
Initilizer block one
Main method

Initializer block has executed twice because created two objects for InitializerExample class.

Initializer block will be invoked upon object creation. This block is invoked how many time objects are created.

We will add now constructor for class "InitializerExample" as below.



public InitializerExample(){

        System.out.println("InitializerExample Constructor");

    }


Output:


Initilizer block one
InitializerExample Constructor
Initilizer block one
InitializerExample Constructor
Main method

we can observe that initializer block is invoked before constructor call.


Why do we use or What is the usage of "Initializer block".?

We can perform some other operations before constructor call or default values initialization of instance variables.


Static Initializer block:


Static is special keyword in Java, which enables to access methods or variables without creating object for it or by class name.


See article on Static in Java.


Static initializer block Example:

package com.java.w3schools.core.initializer;

/**

 * @author Java-W3schools Blog

 * @File Name StaticBlock.java

 */

public class StaticBlock {
    public StaticBlock() {

        System.out.println("StaticBlock constructor..");
    }

    static {
        System.out.println("Static block...");
    }
}

package com.java.w3schools.core.initializer;

/**
 * @author Java-W3schools Blog
 * @File Name StaticBlockMain.java
 */

public class StaticBlockMain {

    public static void main(String[] args) {

        StaticBlock staticBlockOne = new StaticBlock();

        StaticBlock staticBlockTwo = new StaticBlock();
    }
}


Output:

Static block...
StaticBlock constructor..
StaticBlock constructor..

Defined StaticBlock class with default constructor and static initializer block. In StaticBlockMain class, we have created two objects for StaticBlock class. But, we could see only once static initializer block has executed.

So, Only once static block can be executed even create 100 objects.

Try below.
package com.java.w3schools.core.initializer;

/**
 * @author Java-W3schools Blog
 * @File Name StaticBlock.java
 */

public class StaticBlock {
   
    static{
        System.out.println("Static block...one");
    }
    public StaticBlock() {

        System.out.println("StaticBlock constructor..");
    }
    {
        System.out.println("Normal initilizer block..");
    }

    static {
        System.out.println("Static block...Two");
    }   
}


Output:


Static block...one
Static block...Two
Normal initilizer block..
StaticBlock constructor..
Normal initilizer block..
StaticBlock constructor..


Java api Static Inner class :



  private static class IntegerCache
  {
    static final int low = -128;
    static final int high;
    static final Integer[] cache;
 
    private IntegerCache() {}

    static
    {
      int i = 127;
      String str = VM.getSavedProperty("java.lang.Integer.
IntegerCache.high");

      if (str != null)
      {
        j = Integer.parseInt(str);
        j = Math.max(j, 127);
        i = Math.min(j, 2147483518);
      }

      high = i;
      cache = new Integer[high - -128 + 1];
      int j = -128;
      for (int k = 0; k < cache.length; k++) {
        cache[k] = new Integer(j++);
      }
    }
  }

Static Variable and block invoking:



package com.java.w3schools.core.initializer;

class StaticClass {
    public static String value;

    static {
        value = "Static variables are not eligible for Garbage Collection";
        System.out.println("Static block has executed...");
    }
}

public class StaticClassMain {
    public static void main(String[] args) {
        System.out.println("main class :: "+StaticClass.value);
    }
}


Output:


Static block has executed...
main class :: Static variables are not eligible for Garbage Collection


StaticClassMain class, we have not created object for StaticClass class. But, identified that static block has executed.

1 comment:

Please do not add any spam links in the comments section.