Welcome to Java Jeopardy!
Alex, I’ll take Initialization for $500.
“A block of code that the Java compiler copies into every constructor.”
What is an instance initializer block.
In the field, it’s unlikely to see anything but the standard constructor initialization. If you go through the Java Tutorial (“Java Trail”) on Classes and Objects, though, you’ll learn that Java supports some interesting other ways to initialize both instance members and static members of a class.
These include static initialization blocks, instance initialization and final methods. I’ll describe each of these in turn, but it will likely be easier to experience it for yourself. At the end of this post, I’ve included a Github Gist of a Java class, InitializationBlocksInANutshell, using all forms of initialization at once and printing a line to the console in each of them. This is an easy way to see the order of execution of the different kinds of initialization. For fun, try rearranging them. I found that putting final method initialization below an instance initialization block rather than above changed their order of execution. So too did the positioning of static intialization blocks within the class. Beware!
As the term implies, this is a block of code to perform initalization of anything in the static context. As such, it runs when the class is loaded into the JVM. If you want an easy layperson’s way of understanding it, any members declared static will run “first.” The purpose of the static initialization block is to initialize any static members of the class. One good common use for this is to populating any collections (like sets or maps) the class uses as reference material.
As mentioned above, initialization blocks are one way to share code between constructors. Here is what the referenced Java Trail says:
The Java compiler copies initializer blocks into every constructor. Therefore, this approach can be used to share a block of code between multiple constructors
These are methods marked final and called during variable declaration. Here is what the referenced Java trail says about final method initialization:
This is especially useful if subclasses might want to reuse the initialization method. The method is final because calling non-final methods during instance initialization can cause problems.
I ran the following code through the Java 8 compiler and runtime. For a good time, try experimenting with the order of the i and staticVar variables in relation to their corresponding intialization or static initialization blocks.
This post originally appeared on code.scottshipp.com.