STATIC INITIALISERS

CONTENTS

1. Overview


1. OVERVIEW

Initialisation of instance variables is handled by class constructors (default or user defined); initialisation of class variables (field variables) is handled on decalaration within the class definition. However, the situation may arrise where we do not know the nature of the class initialisation till run time. Suppose we have a class variable which comprises an array of 10 integers to which we wish to assign 10 random numbers. A possible solution is to assign the numbers as soon as we start running the program as shown in Table 1.

// Example Program
// Frans Coenen
// 10 February 2000
// Dept Computer Science, University of Liverpool

class ExampleProgram {
    
    // ------------------- FIELDS ------------------------ 
    
    static int[] myArray = new int[10]; 
    
    // ------------------ METHODS ------------------------ 
    
    /* Main method */
    
    public static void main(String[] args) {
        int index;
	
        // Load array
	
        for (index=0;index < myArray.length;index++) {
	    myArray[index] = (int) (Math.random()*100);
	    }
        
	// Output array
	
	for (index=1;index < myArray.length;index++) {
	    System.out.println(myArray[index]);
	    }
	}
    }

Table 1: Simulating initilisation using assignment at run time

Alternatively we can use what is called a static initialiser as shown in table 2. A static initialiser is a block of code, preceded by the keyword static, which is automatically invoked by the Java Virtual machine (JVM) before the main method is executed.

// Example Program
// Frans Coenen
// 10 February 2000
// Dept Computer Science, University of Liverpool

class ExampleProgram {
    
    // ------------------- FIELDS ------------------------ 
    
    static int[] myArray = new int[10]; 
    
    // Stativ initialiser
    
    static {
        for (int index=0;index < myArray.length;index++) {
	    myArray[index] = (int) (Math.random()*100);
	    }
	}
	
    // ------------------ METHODS ------------------------ 
    
    /* Main method */
    
    public static void main(String[] args) {
        
	// Output array
	
	for (int index=0;index < myArray.length;index++) {
	    System.out.println(myArray[index]);
	    }
	}
    }

Table 2: Using a static initialiser

Note that a class may have a series of static initialisers in which case the system wuill execute all the static initialisers in sequence.




Created and maintained by Frans Coenen. Last updated 17 September 2000