Static Initialization Blocks


We have just discussed how constructors are used to initialize the instance variables of a class. But how do you initialize class (static) variables? Class variables can be initialized either when they are declared or by using a static initialization block. This is simply a block of code preceded by the static keyword.

 static {    //  body of static initialization block } 

A static initialization block is not explicitly called. It is executed one time by the system when the class is first loaded.

Example: Using Static Initialization Blocks

This simple example shows how a static initialization block provides an initial value for a class variable. The main() method never actually calls the static initialization block. The block is called by the system when the class is loaded.

 public class StaticInitDemo {   public static int MAX_ITERATIONS;   static {     MAX_ITERATIONS = 50;   }   public static void main(String args[]) {     System.out.println("MAX_ITERATIONS = "+                         MAX_ITERATIONS);   } } 

Output ”

 MAX_ITERATIONS = 50 


Technical Java. Applications for Science and Engineering
Technical Java: Applications for Science and Engineering
ISBN: 0131018159
EAN: 2147483647
Year: 2003
Pages: 281
Authors: Grant Palmer

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net