What is the difference between a static and a non-static initialization code block
The code block with the static modifier signifies a class initializer; without the static modifier the code block is an instance initializer.
Class initializers are executed in the order they are defined (top down, just like simple variable initializers) when the class is loaded (actually, when it's resolved, but that's a technicality).
Instance initializers are executed in the order defined when the class is instantiated, immediately before the constructor code is executed, immediately after the invocation of the super constructor.
If you remove static
from int a
, it becomes an instance variable, which you are not able to access from the static initializer block. This will fail to compile with the error "non-static variable a cannot be referenced from a static context".
If you also remove static
from the initializer block, it then becomes an instance initializer and so int a
is initialized at construction.
Uff! what is static initializer?
The static initializer is a static {}
block of code inside java class, and run only one time before the constructor or main method is called.
OK! Tell me more...
- is a block of code
static { ... }
inside any java class. and executed by virtual machine when class is called. - No
return
statements are supported. - No arguments are supported.
- No
this
orsuper
are supported.
Hmm where can I use it?
Can be used anywhere you feel ok :) that simple. But I see most of the time it is used when doing database connection, API init, Logging and etc.
Don't just bark! where is example?
package com.example.learnjava;
import java.util.ArrayList;
public class Fruit {
static {
System.out.println("Inside Static Initializer.");
// fruits array
ArrayList<String> fruits = new ArrayList<>();
fruits.add("Apple");
fruits.add("Orange");
fruits.add("Pear");
// print fruits
for (String fruit : fruits) {
System.out.println(fruit);
}
System.out.println("End Static Initializer.\n");
}
public static void main(String[] args) {
System.out.println("Inside Main Method.");
}
}
Output???
Inside Static Initializer.
Apple
Orange
Pear
End Static Initializer.
Inside Main Method.
Hope this helps!
The static
block is a "static initializer".
It's automatically invoked when the class is loaded, and there's no other way to invoke it (not even via Reflection).
I've personally only ever used it when writing JNI code:
class JNIGlue {
static {
System.loadLibrary("foo");
}
}