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?
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.
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.
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.
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.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With