Had a discussion about java initializer blocks with a friend a while back, and thought I’d summarize some of the points here, along with tested code examples.
Static Initializer
public class initializerTest
{
private final static String var1
;
private static String var2
;
static {
var1
= "test";
var2
= "a";
System.
out.
println("hello");
initializerTest t
= new initializerTest
();
}
public initializerTest
() {
System.
out.
println(var1
);
System.
out.
println(var2
);
}
}
Output:
- Can initialize final variables
- Can run code
- Can instantiate classes
- Initializer blocks run before constructors
The output seen here is produced (in order) by:
- Initializer is run when the class definition is loaded, and hello is printed out
- Initializer instances a copy of initializerTest, which causes the constructor to print test\n a
- The main method that instanced a copy of initializerTest has the object’s constructor called, resulting in another test\n a
Non-static initializer
Of course the same block works without the static keyword, and works as a non-static initializer
Exception handling
Error: Unhandled exception, Initializer does not exit normally
Error: Initializer does not exit normally
No errors:
{
try {
if (var1.
equals("a"))
throw new Exception("this is checked");
} catch (Exception e
) {
//do nothing
}
}
- Initializer block must exit normally (no unhandled checked exception)
- Unchecked exceptions can be thrown
Posted in Java.
Tagged with initializer, initializer block, java.