Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Difference between static block and assigning static in class?

Tags:

java

static

Is there any difference between following two initializations of static variables:

class Class1 {    
    private static Var var;

    static {
        var = getSingletonVar();
    }  
}

class Class2 {
    private static var = getSingletonVar;
}

Are these two different ways of initializing a static variable functionally the same?

like image 656
blue-sky Avatar asked Jun 05 '14 10:06

blue-sky


People also ask

What is difference between static block and static method?

Static methods belong to the class and they will be loaded into the memory along with the class, you can invoke them without creating an object. (using the class name as reference). Whereas a static block is a block of code with a static keyword. In general, these are used to initialize the static members.

What is the difference between static and instance block?

Static blocks can be used to initialize static variables or to call a static method. However, an instance block is executed every time an instance of the class is created, and it can be used to initialize the instance data members.

What is static and static block in Java?

In a Java class, a static block is a set of instructions that is run only once when a class is loaded into memory. A static block is also called a static initialization block.

What do you mean by static block?

In a static block, a value is defined, and in the main class, an instance of the Demo class is created and the static integer is accessed from there. © Copyright 2022.


2 Answers

Yes, its functionally the same.

From Java doc

There is an alternative to static blocks — you can write a private static method:

class Whatever {
    public static varType myVar = initializeClassVariable();

    private static varType initializeClassVariable() {

        // initialization code goes here
    }
}

The advantage of private static methods is that they can be reused later if you need to reinitialize the class variable.
like image 100
Sajan Chandran Avatar answered Oct 21 '22 14:10

Sajan Chandran


The result will be same.

In both the cases static variable will get initialized with class loading.

static methods and static class blocks are two different things. static methods need to be called where as static class block automatically gets executed with class loading.

like image 33
Shail016 Avatar answered Oct 21 '22 15:10

Shail016