Login | Register   
LinkedIn
Google+
Twitter
RSS Feed
Download our iPhone app
TODAY'S HEADLINES  |   ARTICLE ARCHIVE  |   FORUMS  |   TIP BANK
Browse DevX
Sign up for e-mail newsletters from DevX


Tip of the Day
Language: Java
Expertise: Intermediate
Dec 9, 1998

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 block
9.       static {
10.       System.out.println("2::str = " + str);
11.       str = "Static";
12.    }
13. 
14.    // Main routine to test the class
15.    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 = Default
1:: 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.

Ajit Sagar
 
Comment and Contribute

 

 

 

 

 


(Maximum characters: 1200). You have 1200 characters left.

 

 

Sitemap
Thanks for your registration, follow us on our social networks to keep up-to-date