/home/wpollock1/public_html/AJava/InitBlockDemo.java

/* Demo of initialization blocks in Java.
 *
 * Written 8/2005 by Wayne Pollock, Tampa Florida USA
 * Updated 2/2021: expanded the details on the steps.
 *

These are the 12 steps to initialize an object f from the code Foo f=new Foo();
 1. The Classloader locates Foo.class file on disk, and any dependent classes
    (e.g., superclasses).
 2. Byte code is verified.
 3. Class objects for dependent classes are found on disk, created, and
    initialized (each using these same steps 1-6).
 4. Sufficient memory is allocated for all Class object's fields, including all
    static fields in the class Foo.
 5. All static fields are initialized to default (zero, false, null) values.
 6. Static fields and static initialization blocks are executed in the order
    they appear.

The remaining steps are per-object:

 7. Sufficient memory is allocated for all instance fields, included inherited
    ones.
 8. All instance properties are initialized to default (zero, false, null) values.
 9. The parent class' instance fields are initialized (including any
    initialization blocks).
10. The parent class' constructor is run to finish initializing inherited fields.
11. Instance variable initialization expressions and initialization blocks are
    executed in the order they appear.
12. The body of the matched constructor is executed.

Steps 1–6 occur only once in the lifetime of the JVM.  The rest occur each time
a new object is created.
 */

class InitBlockDemo {
   private static int nextID;
   public int idNum;
   public String name;

   static {
      nextID = 1;  // complex DB lookup goes here
      // Add shutdown hook here
   }

   {
      idNum = nextID++;   // Run before any constructor
   }

   InitBlockDemo () {
      this( "unknown" );  // Constructor chaining
   }

   InitBlockDemo ( String name ) {
      // Object's no-arg constructor is invoked here.
      this.name = name;
   }

   public static void main ( String [] args ) {
      InitBlockDemo ibd1 = new InitBlockDemo( "Hymie" );
      InitBlockDemo ibd2 = new InitBlockDemo();
      System.out.println( "ibd2.idNum = " + ibd2.idNum );
   }
}