devxlogo

Pre-construction Initialization

Pre-construction Initialization

Java provides a construct that offers functionality similar to inline functions in C++. In Java, this feature is provided by static intializers. Static initializers are blocks of code within a class that are outside the scope of a method. The code in a static initializer block is executed only once, when the class is loaded. The code is executed in the same order as it is declared in the class. The following code excerpt illustrates the use of a static initializer block:

 1.     public class TestStaticInitializer {2.       static String str = "Default";3. 4.       public TestStaticInitializer() {5.         System.out.println("1::str = " + str);6.       }7.  8.       // Static initializer block9.       static {10.       System.out.println("2::str = " + str);11.       str = "Static";12.    }13. 14.    // Main routine to test the class15.    public static void main(String[] args) {16.      TestStaticInitializer tsi = new TestStaticInitializer();17.    }18. }

A static string is declared on Line 2 and set to “Default.” Next, a static initializer block prints the string out and resets it to the value “Static” on Lines 8-12. The constructor on Lines 4-6 merely prints the variable out.

The output of this program is:

 2:: str = Default1:: str = Static

When the class is loaded (because it was constructed) on line 17, lines 9-12 are executed before the constructor is called. The code in static initializer blocks is always executed when the class is loaded and before any method in the class is executed.

Static initializer blocks may be used for executing code that initializes the state of the object or for providing debugging functionality. However, overuse of this feature can lead to complex and unreadable code.

devxblackblue

About Our Editorial Process

At DevX, we’re dedicated to tech entrepreneurship. Our team closely follows industry shifts, new products, AI breakthroughs, technology trends, and funding announcements. Articles undergo thorough editing to ensure accuracy and clarity, reflecting DevX’s style and supporting entrepreneurs in the tech sphere.

See our full editorial policy.

About Our Journalist