Java Static Initializers - What are static Initializers?

What are Static Initializers?

A static initializer block resembles a method with no name, no arguments, and no return type. There is no need to refer to it from outside the class definition.

Syntax :
static
{
    //CODE
}

The code in a static initializer block is executed by the virtual machine when the class is loaded.

Because it is executed automatically when the class is loaded, parameters don't make any sense, so a static initializer block doesn't have an argument list.

What are Static Initializers? Explain with an example.

Static inializer is a code block with a name ‘static’. A class can contain one or more static initializer blocks. The code in the static initializer block will be executed first followed by the code in the constructor, exactly once in the order they appear in the class. While the class is loaded, the executions in the static initializers take place.

Example :
class Test
{
      static int stNumber;
      int number;
      Test()
      {
          number = 10;
      }
      static
      {
          stNumber=30;
      }
             …… // other methods here
}

In the above example, the code in static initializer will be executed first followed by the code in the constructor.

Purpose of the wait (), notify (), and notifyAll() methods
notify() Wakes up a single thread that is waiting on this object's monitor...
Advantage of event-delegation model over the earlier event inheritance model?
Event-delegation model allows a separation between a component's design.....
Difference between Boolean & operator and the && operator
A & B In this, both the operands A as well as B are evaluated and then ‘&’ is applied to them...
Post your comment