What Is an Initializer in Java?

An initializer is a line of code (or a block of code) 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.

The simplest initializers are those that declare and initialize fields. For example:

class Class1
{
    public int x = 0;
    // other class constructors and members go here
}

The variable x is declared and initialized to a value of 0 (zero).

An initializer can also be a block of code enclosed within parentheses, as in this example:

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

Here are a few other nuggets 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.

  • Although including all initializers at the beginning of the class is common — before any constructors or methods — this ordering isn’t a requirement. Initializers can appear anywhere within a class.

  • Add a Comment
  • Print
  • Share
blog comments powered by Disqus
Advertisement

Inside Dummies.com

Dummies.com Sweepstakes

Win $500. Easy.