As an alternative to static blocks, Oracle docs are suggesting to call a method(s) and the example is using a variable assignment:
public static varType myVar = initializeClassVariable();
The advantage of private static methods is that they can be reused later if you need to reinitialize the class variable.
But if I don't need (and want to avoid unused) extra variable and also return statement in my static block, what is a better way to call static code?
Calling a static method in the constructor is wrong design for executing static code once (constructor can be private
for utility class) for static block
public MyClass() {
MyClass.initializeClassVariable();
}
So is the only improvement is reducing variable access level to private ?
private static varType myVar = initializeClassVariable();
Or a better approach is to keep static block and add the method there?
static {
initializeClassVariable();
}