import java.util.ArrayList; // This class provides a demo of static intializers. // In the example below, there are three static arraylists, each // of which is initalized in a different way. // The first ArrayList, elPulpoMechanical, is initialized using a // static initalizer block. The seecond ArrayList, jellyfishHeaven, // is initailized using a call to a static method. // These two initializations are performed at the time that the first // instance of this class is instantiated. Neither of these initializations // is ever called again (well at least until this class is reloaded by // anther ClassLoader, for example when the 'java' command is called by the // operation system again). // The third ArrayList, rydeen, is initialized using an initalizer block. // Unlike the static initialization techniques discussed above, this code is // called again EVERY TIME a new StaticInitialization is performed. As Oracle puts // it, "The Java compiler copies initializer blocks into every constructor." // The fourth ArrayList, zebra, is initialized using the constructor. Naturally, // this code will execute every time that a StaticInitializationDemo object is // instantiated (though unlike rydeen, the code is written to prevent the // static variable fromy being set more than once). // Bottom line: We recommend that you use one of the first two approaches! public class StaticInitializationDemo { public static ArrayList elPulpoMechanical; public static ArrayList jellyfishHeaven = createArrayList(10); public static ArrayList rydeen; public static ArrayList zebra; static { elPulpoMechanical = new ArrayList(); elPulpoMechanical.add("Watskeburt?!"); } private static ArrayList createArrayList(int numStrings) { ArrayList tempArrayList = new ArrayList(); for (int i = 0; i < numStrings; i++) tempArrayList.add("Sweet jellyfish!"); return tempArrayList; } { rydeen = new ArrayList(); rydeen.add("Watskeburt?!"); } public StaticInitializationDemo() { if (zebra == null) zebra = createArrayList(10); } }