4

I am learning C# and JAVA I found Static Constructor in C# which is used to initialize any static data, or to perform a particular action that needs to be performed once only. It is called automatically before the first instance is created or any static members are referenced.

For Example:

class SimpleClass
{
    // Static variable that must be initialized at run time. 
    static readonly long baseline;

    // Static constructor is called at most one time, before any 
    // instance constructor is invoked or member is accessed. 
    static SimpleClass()
    {
        baseline = DateTime.Now.Ticks;
    }
}

My Question is that how can I gain same functionality in JAVA is there any way ???

Bilal Maqsood
  • 1,029
  • 3
  • 15
  • 39

2 Answers2

6

You may use static initialization block like this -

class SimpleClass
{
    static{

    }

}  

The static block only gets called once, no matter how many objects of that type is being created.

You may see this link for more details.

Update: static initialization block is called only when the class is loaded into the memory.

Community
  • 1
  • 1
Razib
  • 10,521
  • 10
  • 50
  • 75
5

You have static initializer block.

static final long baseline;
static {
    baseline = ...
}
Eran
  • 374,785
  • 51
  • 663
  • 734