Array Initialization in Java with Example

Once the array is created, the next step is to put the elements (or values) into the array created at compile time. This process is called initialization of array in Java.

The general syntax to initialize elements of array when we declare an array or when we create an array object using the new operator is as follows:

arrayname[index] = value;

For example, the following code initializes values to the various positions in the array.

 // Declaring an array variable, creating an array, and assigning the reference of the array to the variable.
      int[ ] num = new int[10];

// Array Initialization in Java.
     num[0] = 20;  // Assign 20 to the first element of num.
     num[1] = 30;  // Assign 30 to the second element of num.
     num[2] = 40;
     num[3] = 60;
     num[4] = 80;
     num[5] = 100;
     num[6] = 120;
     num[7] = 150;
     num[8] = 200;
     num[9] = 300; // Assign 300 to the tenth element of num. 

The above code creates an array of 10 elements and initializes its values 20, 30, 40, and so on. The size (length) of the array must be the same as the number of values passed in the array initialization list.

Look at the below figure to understand better.

Array initialization in Java

Java throws a runtime exception to refer to a non-existing element of an array.

For example, using num[10] in the above code will throw a runtime exception because num has the length of 10 and num[10] refers to the eleventh element which is non-existing.

Java creates an array starting with the index of 0 and ends with a value one less than the size specified. The index for the first element is 0, the second element 1, the third element 2, and so on.

Array indices are known as zero-based indexing. The index for the last element of an array is the size (length) of array minus 1 (i.e. arrayname.length – 1).

Default Initialization of Array Elements in Java


When an array is created, the individual elements of an array are automatically initialized with the default value.


For example, the elements of a numeric array are initialized to zero, boolean array elements to false, and char elements to ‘\u0000’. Array elements of class type are initialized to null.

The following snippet of code are examples of the array initialization:

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

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

// An example of class type (means reference type) array. 
// strArr[0] and strArr[1] are initialized to null.
     String[ ] strArr = new String[2]

// Another example of a class type array.
// All 50 elements of the Employee array are initialized to null.
     Employee[ ] emp = new Employee[100];

Let’s take a simple example program where we will see the default array initialization for instance and local variables. Look at the source code.

Program source code 1:

package arraysProgram;
public class DefaultArrayInitialization 
{
  private final boolean[] bArr = new boolean[3]; // An instance variable.

 public DefaultArrayInitialization()
 {
 // Print the initial value for elements of the instance variable bArr.
   for (int i = 0; i < bArr.length; i++) 
   {
	 System.out.println("bArr[" + i + "]:" + bArr[i]);
   }
}
public static void main(String[] args) 
{
 System.out.println("Array initialization of int type:");
 int[ ] intArr = new int[3]; // A local array variable.
	
 for (int i = 0; i < intArr.length; i++)
 {
    System.out.println("intArr[" + i + "]:" + intArr[i]);
 }
 System.out.println("\nArray initialization of boolean type:");

// Initial values for bArr elements are displayed inside the constructor.
     new DefaultArrayInitialization();

   System.out.println("\nArray initialization of reference type:");
   String[ ] name = new String[3]; // A local array variable

   for (int i = 0; i < name.length; i++) {
    System.out.println("name[" + i + "]:" + name[i]);
   }
 }
}

Output:
         Array initialization of int type:
         intArr[0]:0
         intArr[1]:0
         intArr[2]:0

         Array initialization of boolean type:
         bArr[0]:false
         bArr[1]:false
         bArr[2]:false

        Array initialization of reference type:
         name[0]:null
         name[1]:null
         name[2]:null

String Array Initialization in Java (Reference type Arrays)


An array with primitive type elements contains values of that primitive type, whereas elements of a reference type array contain the reference to objects.


Suppose we have an array of double type as:

double[ ] dArr = new double[5];

Here, dArr[0], dArr[1] . . . dArr[4] contain double values.

Suppose we have an array of String as:

String[ ] name = new String[5];

Here, name[0], name[1] . . . name[4] contains a reference to a String object. All elements of the name array contain null by default.

We need to create the String reference objects and assign their references to the elements of the array one by one, as shown below:

// Assigning a valid string object reference to all elements of the array.
    name[0] = "Deep";
    name[1] = "Shubh";
    name[2] = "John";
    name[3] = "Reddy";
    name[4] = "Buddy";

In the case of reference type arrays, we must assign a valid object reference to each element before accessing them, otherwise, you will get a runtime error. For example:

// Create an array of String
     String[ ] empName = new String[2];

// A runtime error as empName[0] is null.
     int len = empName[0].length();

// Assigning a valid string object reference to all elements of the array.
     empName[0] = "John";
     empName[1] = "Shubh";

// Now we can get the length of the first element.
     int len2 = empName[0].length(); // Correct. len2 has value 4.

The concept of initialization of the String reference type array can be applied to all reference types (i.e. all class types). All elements of an array are stored contiguously in the memory location.

In the case of a class type array, the elements of array store references of objects, not objects they are referring to. These references in the elements are stored contiguously in the memory location.

The objects are stored on the heap memory and their locations are, typically, not contiguous.

Array Initializer in Java


Java provides a shorthand notation, known as array initializer which combines the declaration, creation, and initialization of an array in one statement using the following syntax:

datatype[ ] arrayname = {value0, value1, value2 . . ., valuen};

For example:
// Initialize the array at the time of declaration.
     double[ ] number = {2.5, 3.5, 4.5, 5.5}; // List of values separated by commas and surrounded by curly braces ({}).

The above statement declares, creates, and initializes the array number with four elements, which is similar to the following statements:

double[ ] number = new double[4];
number[0] = 2.5;
number[1] = 3.5;
number[2] = 4.5;
number[3] = 5.5;

Alternatively, we can also initialize elements of an array like this:

int[ ] empId = new int[ ]{1, 2, 3, 4, 5};

Here, we cannot specify the length of an array if specifying the array initialization list. The length of the array is the same as the number of elements specified in the array initialization list.

It is possible to create an empty array list like this:

int[ ] emptyNumList = { };

For a class type array, we can specify the list of objects in the initialization list. The following snippet of code is an example of array initialization for the String class.

// Create a String array with two Strings "Orange" and "Sky blue"
    String[ ] colors = {new String("Orange"), new String("Sky blue")};

// We can also use String literals.
    String[ ] colors = {"Orange", "Sky blue"};

The following snippet of code is an example of array initialization for Employee type. Assume that the Employee class exists and it has a constructor, which takes an employee id as an argument.

// Create an Employee array with two Employee objects.
    Employee[ ] emp = new Employee[ ]{new Employee(125536), new Employee(22536)};

Accessing Array Elements in Java


The elements of an array can be accessed through the index enclosed in brackets. The general syntax to represent each element in the array is as follows:

arrayname[index];

For example, suppose we have an array of length 5, the indexes of the array elements would be 0, 1, 2, 3, and 4.

Consider the following statement:

int[ ] stRollNo = new int[5];

The length of the stRollNo array is 5; its elements can be accessed as stRollNo[0], stRollNo[1], stRollNo[2], stRollNo[3], and stRollNo[4]. We can assign values to elements of an array as follows:

stRollNo[0] = 5; // Assign 5 to the first element of stRollNo
stRollNo[1] = 6; // Assign 6 to the second element of stRollNo.
stRollNo[2] = 7; // Assign 7 to the third element of stRollNo.
stRollNo[3] = 8; // Assign 8 to the fourth element of stRollNo.
stRollNo[4] = 9; // Assign 9 to the fifth element of stRollNo.

Let’s understand various kinds of example programs based on array initialization in java.

Example Program based on Array Initialization


1. Let’s create a program where we will print values of an initialized array of 5 elements.

Program source code 1:

package arraysProgram;
public class ArrayEx 
{
public static void main(String[ ] args) 
{
// Initializing elements into an array.
   int num[ ] = {18, 0, 1, 2, 45};
  
// Displaying elements of array using for loop.
   for(int i = 0; i < num.length; i++)
   {
	 System.out.println("The element at " +i+ " position is: " +num[i]);
   }
 }
}
Output:
        The element at 0 position is: 18
        The element at 1 position is: 0
        The element at 2 position is: 1
        The element at 3 position is: 2
        The element at 4 position is: 45

2. Let’s create a program where we will initialize a string array with elements and display them on the console one by one without using for loop.

Program source code 2:

package arraysProgram;
public class ArrayEx {
public static void main(String[] args) 
{
// Creating a String array object.	
     String[ ] city = new String[5];
   
// Initializing array with name of cities.   
    city[0] = "Dhanbad";
    city[1] = "Mumbai";
    city[2] = "Ranchi";
    city[3] = "Kolkata";
    city[4] = "New York";
 
// Displaying name of cities based on index value. 
   System.out.println("City at 0 position: " +city[0]);
   System.out.println("City at 1 position: " +city[1]);
   System.out.println("City at 2 position: " +city[2]);
   System.out.println("City at 3 position: " +city[3]);
   System.out.println("City at 4 position: " +city[4]);
 }
}
Output:
         City at 0 position: Dhanbad
         City at 1 position: Mumbai
         City at 2 position: Ranchi
         City at 3 position: Kolkata
         City at 4 position: New York

3. Let’s create a program where we will initialize an array of char type and display them on the console. It will print one statement. No need to use for loop in the char case.

Program source code 3:

package arraysProgram;
public class ArrayEx 
{
public static void main(String[ ] args) 
{
// Initializing elements into an array.
     char city[ ] = {'D','h','a','n','b','a','d'};
  
// Displaying elements of array of char type.
     System.out.println("Name of city: " +city);
 }
}
Output:
            Dhanbad

4. Let’s create a program where we will initialize an array with values entered by the user using Scanner class and calculate the sum of these numbers. Here, we will use for loop in the program.

Program source code 4:

package arraysProgram;
import java.util.Scanner;
public class ArrayEx {
public static void main(String[] args) 
{
// Create a scanner of object using System.in.
     Scanner sc = new Scanner(System.in);
     int num[ ] = new int[5]; // Creating an array object. 
   
  System.out.print("Enter " + num.length + " integer values: ");
  for (int i = 0; i < num.length; i++)
	num[i] = sc.nextInt();
  
// Calculating the sum of input values.
    int sum = 0;
    for(int i = 0; i< num.length; i++){
           sum += num[i];	
      }
	
// Displaying sum of input values entered by user.
     System.out.println("Sum: " +sum);
 }
}
Output:
          Enter 5 integer values: 
          20
          30
          40
          50
          60
         Sum: 200

5. Let’s create a program where we will initialize the list of objects of Student types in the array. Student class has a constructor that accepts names and roll nos as arguments. Look at the following source code to understand better.

Program source code 5:

package arraysProgram;
public class Student 
{
String name;
int rollNo;
Student(String name, int rollNo) {
  this.name = name;
  this.rollNo = rollNo;
 }
}
package arraysProgram;
public class ArrStudent {
public static void main(String[] args) 
{
// Create a String array with three Student objects.	
  Student[ ] st = new Student[ ]
  { new Student("Deep", 01), 
     new Student("John", 02), 
     new Student("Herry", 03)
  };
// Accessing elements of the specified array.
for(int i = 0; i < st.length; i++)
{
    System.out.println("Name: " +st[i].name+ ", "+"Roll no: " +st[i].rollNo);	
  }
 }
}
Output:
         Name: Deep, Roll no: 1
         Name: John, Roll no: 2
         Name: Herry, Roll no: 3

6. Let’s make a program where we will access an element outside from array size. In this case, JVM will throw a runtime exception named ArrayIndexOutOfBoundsException that tells “array has been accessed with an illegal index”. The index is either negative or greater than or equal to the size of an array.

Program source code 7:

package arraysProgram;
public class IllegalAcsess {
public static void main(String[] args) 
{
 int[] arr = new int[2];
 arr[0] = 30;
 arr[1] = 20;

for (int i = 0; i <= arr.length; i++)
  System.out.println(arr[i]);
 }
}
Output:
          30
          20
         Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 2
         at arraysProgram.IllegalAcsess.main(IllegalAcsess.java:10)

Hope that this tutorial has covered almost all the important points related to array initialization in java with example programs. I hope that you will have understood the basic concepts of array initialization and its related programs.
Thanks for reading!!!