I am a little bit doubtful about the proper way of initializing static variables.
I've realized that I can directly assign a value to a static variable at the definition time, like in:
public class MyClass {
// Direct initialization
public static int counter = 0;
Also, I have seen that you can use a static block, like in:
public class MyClass {
public static int counter;
static {
counter = 0;
}
}
Even, I have surprisingly seen that you can also access static variables from class constructors and set them a value from there, like in:
public class MyClass {
public static int counter;
public MyClass() {
this.counter = 0;
}
public MyClass( int a ) {
this.counter = a;
}
}
My question is: What's the proper way or underlying difference among using one or another type of initialization when dealing with static variables?
I have also wrote and executed the following code, so I could realize how the variable is being modified along the program execution.
public class StaticVariable {
static int a = 0;
public StaticVariable( int b ) {
// The constructor parameter b is ignored
System.out.println( "[Inside 1-parameter constructor] Current value of \"a\": " + a + " ." );
System.out.println( "[Inside 1-parameter constructor] Value of \"a\" was increased in one ..." );
a++;
}
public StaticVariable() {
System.out.println( "[Inside parameterless constructor] Current value of \"a\": " + a + " ." );
System.out.println( "[Inside parameterless constructor] Value of \"a\" was increased in one ..." );
a++;
}
static {
System.out.println( "[Inside static block] Initial value of \"a\": " + a + " ." );
System.out.println( "[Inside static block] Value of \"a\" was increased in one ..." );
a++;
}
public static void main( String[] args ) {
System.out.println( "[main method] Current value of \"a\": " + StaticVariable.a + " ." );
StaticVariable object = new StaticVariable();
System.out.println( "[main method] Current value of \"a\": " + StaticVariable.a + " ." );
StaticVariable object2 = new StaticVariable( 10 );
System.out.println( "[main method] Current value of \"a\": " + StaticVariable.a );
System.out.println( "[main method] Directly setting value of \"a\" with 560" );
StaticVariable.a = 560;
System.out.println( "Updated value of \"a\": " + StaticVariable.a );
}
}
Thanks in advance.