Static initializers
Home ] Up ] Class vs. Instance Variables ] Usage ] Initialization ] [ Static initializers ]

 

 

Sometimes we need to initialize things in a way that cannot be handled using such simple initializers.

Instance variables have constructor methods to accomplish this.

Static Initializers

Class variables need a different mechanism: static initializers

For example:

class Primes
{
    ...

    private static int nextPrime(int startFrom)
    { 
        /* ... */ 
    }

    ...

    //// Data ////
    private static int knownPrimes = new int[4];

    static
    {
        knownPrimes[0] = 2;
        for (int i = 1; i < knownPrimes.length; i++)
            knownPrimes[i] = nextPrime(knownPrimes[i-1]);
    }
}

A static initializer is like a class method, except:

  • It has no name
  • It accepts no arguments
  • It returns no value

There can be any number of static initializers -- they are executed in lexical order when the class is loaded.

Static initializers are used, among other places, in classes that implement native methods (much later...).

Initialization Blocks

You can also have an initialization block that does not have a static keyword prefix.  It allows you to initialize instance fields, or to execute arbitrary code at instance initialization:

public class InitializerTest
{
  public static void main(String[] args)
  {
    InitializerTest test1 = new InitializerTest();
    InitializerTest test2 = new InitializerTest();
  }

  // Initialization block
  {
    System.out.println("Executing initialization block");
    System.out.println("Count now " + ++m_count);
  }
  static int m_count = 0;
}

which produces:

Executing initialization block
Count now 1
Executing initialization block
Count now 2

There are a number of potentially useful applications of this technique.

 

This page was last modified on 02 October, 2007