A non-static initialization block in Java

Java 8Object Oriented ProgrammingProgramming

Instance variables are initialized using initialization blocks. These blocks are executed when the class object is created and before the invocation of the class constructor. Also, it is not necessary to have initialization blocks in the class.

A program that demonstrates a non-static initialization block in Java is given as follows:

Example

 Live Demo

public class Demo {
   static int[] numArray = new int[10];
   {
      System.out.println("\nRunning non-static initialization block.");
      for (int i = 0; i < numArray.length; i++) {
         numArray[i] = (int) (100.0 * Math.random());
      }
   }
   void printArray() {
      System.out.println("The initialized values are:");
      for (int i = 0; i < numArray.length; i++) {
         System.out.print(numArray[i] + " ");
      }
      System.out.println();
   }
   public static void main(String[] args) {
      Demo obj1 = new Demo();
      System.out.println("For obj1:");
      obj1.printArray();
      Demo obj2 = new Demo();
      System.out.println("For obj2:");
      obj2.printArray();
   }
}

Output

Running non-static initialization block.
For obj1:
The initialized values are:
96 19 14 59 12 78 96 38 55 85
Running non-static initialization block.
For obj2:
The initialized values are:
38 59 76 70 97 55 61 81 19 77
raja
Published on 15-Feb-2019 06:16:57
Advertisements