In this post, you will learn to:

  • Describe initializers.
  • State the syntax of variable initializers.
  • State the syntax of instance initializers.

Concept of Initializers

Initializers are small pieces of code embedded in curly braces that perform initialization. Besides using constructors for initializing, initializers can be used for initializing. The different types of initializers are as follows:

Note: static is a keyword in Java. A variable declared using the static keyword is a class variable and not an instance variable, such as static int age. If initializers are declared, these are invoked before constructors are invoked during object instantiation.

Object Field Initializers

Object field initializers also known as instance variable initializers are declared inside a class. An instance variable initializer contains an equal sign and an expression. The following is the syntax for initializing a field with an instance variable initializer.

Syntax:

class <classname>{
   // Object field initialization with value/expression
   <data_type> field1=<value>/<expression>
 }

Object Block Initializers

Object block initializers also known as instance initialization block are declared within the class, but outside the constructor and method definitions. An instance initializer begins with a brace bracket, followed by one or more statements and ends with a brace bracket. The following is the syntax for declaring an instance initializer within a class.

Syntax:

class <classname>{
   // Object block initialization
   {
      //Initialization code
   }
}

The following code demonstrates the working of variable initializers and instance initializers.

Code Snippet:

public class MugsBeer {
   //instance field initialization
   float price=9.50F;
   String materialUsed;
   String make;
   //instance block initialization of materialUsed,make 
   {
      make="Ogilvy";
      materialUsed="Crystal";
      System.out.println("price, materialUsed & make initialized");
   }
   
   MugsBeer() {
      System.out.println("Beer Mugs Constructor");
   }
   
   public static void main(String[] args) {
      MugsBeer x = new MugsBeer();
   }
}

Output:

price, materialUsed and make initialized