Java - Array Elements Initializing

Introduction

Array elements are always initialized.

Array elements of primitive data type are initialized to the default value for their data types.

For example, the numeric array elements are initialized to zero, boolean elements to false, and the reference type elements to null.

The following snippet of code illustrates the array initialization:

// intArray[0], intArray[1] and intArray[2] are initialized to zero by default.
int[] intArray = new int[3];

// bArray[0] and bArray[1] are initialized to false.
boolean[] bArray = new boolean[2];

// An example of a reference type array.
// strArray[0] and strArray[1] are initialized to null.
String[] strArray = new String[2]

// Another example of a reference type array.
// All 100 elements of the person array are initialized to null.
Person[] person = new Person[100];

The following code illustrates the array initialization for an instance variable and some local variables.

Demo

public class Main {
  private boolean[] bArray = new boolean[3]; // An instance variable

  public Main() {
    for (int i = 0; i < bArray.length; i++) {
      System.out.println("bArray[" + i + "]:" + bArray[i]);
    }//from  w  w w .ja  va2s  .  com
  }

  public static void main(String[] args) {

    int[] empId = new int[3]; // A local array variable
    for (int i = 0; i < empId.length; i++) {
      System.out.println("empId[" + i + "]:" + empId[i]);
    }

    System.out.println("boolean array initialization:");

    new Main();

    System.out.println("Reference type array initialization:");

    String[] name = new String[3]; // A local array variable
    for (int i = 0; i < name.length; i++) {
      System.out.println("name[" + i + "]:" + name[i]);
    }
  }
}

Result

Reference Type Array Initializing

Elements of a reference type contain the reference of objects.

Suppose you have an int array of

int[] empId = new int[5];

Here, empId[0],empId[1]...empId[4] contain an int value.

Suppose you have an array of String, like so:

String[] name = new String[5];

name[0], name[1]...name[4] may contain a reference of a String object.

All elements of the name array contain null at this point.

You need to create the String objects and assign their references to the elements of the array one by one as shown:

name[0] = new String("name1");
name[1] = new String("name2");
name[2] = new String("name3");
name[3] = new String("name4");
name[4] = new String("name5");