How to Use Initializers in Java - dummies

By Doug Lowe

An initializer (sometimes called an initializer block) is a lonely block of code in Java that’s placed outside any method, constructor, or other block of code. Initializers are executed whenever an instance of a class is created, regardless of which constructor is used to create the instance.

Initializer blocks are similar to variable initializers used to initialize variables. The difference is that with an initializer block, you can code more than one statement. Here’s a class that gets the value for a class field from the user when the class is initialized:

class PrimeClass
{
 private Scanner sc = new Scanner(System.in);
 public int x;
 {
  System.out.print(
   "Enter the starting value for x: ");
  x = sc.nextInt();
 }
}

You can almost always achieve the same effect by using other coding techniques, which usually are more direct. You could prompt the user for the value in the constructor, for example, or you could call a method in the field initializer, like this:

class PrimeClass
{
 private Scanner sc = new Scanner(System.in);
 public int x = getX();
 private int getX()
 {
  System.out.print("Enter the starting value "
  + "for x: ");
  return sc.nextInt();
 }
}

Either way, the effect is the same.

Here are a few other tidbits of information concerning initializers:

  • If a class contains more than one initializer, the initializers are executed in the order in which they appear in the program.

  • Initializers are executed before any class constructors.

  • A special kind of initializer block called a static initializer lets you initialize static fields.

  • Initializers are sometimes used with anonymous classes.