J2EEOnline J2EE






Java Certification  «Prev  Next»
Lesson 6Initializers
ObjectiveDescribe how static and non-static Initializers are declared and used.

Initializers in Java

Java supports the declaration of special code blocks that are part of a class declaration but not part of a method. These code blocks are referred to as initializers. Two types of initializers are supported: static and non-static.
Initializer: A block of code that is used to initialize a variable.

Static initializers

Static initializer are used to initialize the static variables of a class or invoke the methods of static variables. They are declared as follows:
Static initializer: A block of code that is used to initialize a static variable.
static {
 // Initialization code
}
Static initializers are executed when their class is loaded in the order that they appear in the class declaration. They are not executed when an instance of a class is created. The following program illustrates the use of static initializers. It displays the output abc.

class StaticInitializer {

  // Note that System.out is a static variable.
  static { 
    System.out.print("a");
  }
  
  public static void main(String[] args) {
    System.out.println("c");
  }

  static {
    System.out.print("b");
  }  
}
The output of StaticInitializer is
abc
Non-static initializers
Non-static initializers differ from static initializers in that they are used to update and invoke the methods of non-static variables. They also differ when they are executed. Non-static initializers are not executed when their class is loaded.
They are executed (in the order that they appear) when an instance of their class is created (before the object's constructor). Non-static initializers are declared in the same way as static initializers except that the static keyword is omitted.
The following program illustrates non-static initializers. It displays the value 103.

class Initializer {

  int i = 1;
  int j = 2;
  { 
    j += i;
  }
  
  public static void main(String[] args) {
    new Initializer();
  }    
      
  Initializer() {
    System.out.println(j);
  }

  {
    j += 100;
  }
}
Objects Methods Initializers - Quiz
Click the Quiz link below to check your understanding of objects, methods, and initializers.
Objects Methods Initializers - Quiz