Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Static Initialization Blocks

As far as I understood the "static initialization block" is used to set values of static field if it cannot be done in one line.

But I do not understand why we need a special block for that. For example we declare a field as static (without a value assignment). And then write several lines of the code which generate and assign a value to the above declared static field.

Why do we need this lines in a special block like: static {...}?

like image 781
Roman Avatar asked Mar 10 '10 20:03

Roman


People also ask

Why we use static initialization block in Java?

Instance variables are initialized using initialization blocks. However, the static initialization blocks can only initialize the static instance variables. These blocks are only executed once when the class is loaded.

What are initialization blocks?

Initializer block contains the code that is always executed whenever an instance is created. It is used to declare/initialise the common part of various constructors of a class. The order of initialization constructors and initializer block doesn't matter, initializer block is always executed before constructor.

What is static block used for?

Static block is used for initializing the static variables. This block gets executed when the class is loaded in the memory. A class can have multiple Static blocks, which will execute in the same sequence in which they have been written into the program.

What is the real time use of static initialization block?

1. Static initialization blocks are used to write logic that you want to execute during the class loading. 2. They are used to initialize the static variables.


1 Answers

The non-static block:

{     // Do Something... } 

Gets called every time an instance of the class is constructed. The static block only gets called once, when the class itself is initialized, no matter how many objects of that type you create.

Example:

public class Test {      static{         System.out.println("Static");     }      {         System.out.println("Non-static block");     }      public static void main(String[] args) {         Test t = new Test();         Test t2 = new Test();     } } 

This prints:

Static Non-static block Non-static block 
like image 153
Frederik Wordenskjold Avatar answered Sep 23 '22 05:09

Frederik Wordenskjold