JavaDevNotes.com

Java Initialize Array Examples

An array is a type of variable that can hold multiple values of similar data type. This is very useful for storing values when we don't know how many of them is needed, or when the number of values is very large. The first thing we need to know is how to initialize a Java Array. Below are some code samples on how to perform Java Array Initialization.

Declare Array Without Initialization

Below is an example on how to declare an array in Java without performing initialization:

/**
 * A Simple Example that Declares A Java Array.
 */
public class DeclareJavaArray {
   public static void main(String[] args) {
      int[] testArray;
   }
}

The code declares a variable testArray to be a one dimensional array of type int. Note that since the array was not initialized, the value of the variable is still null at this point of time. Below is another way of declaring an array:
/**
 * A Simple Example that Declares A Java Array.
 */
public class DeclareJavaArray {
   public static void main(String[] args) {
      int testArray[];
   }
}
Notice that the square brackets is at the front of the variable. Both using the square brackets before (int[] testArray;) and after (int testArray[];) are valid.

Initialize Java Array Using Assignment

When we declare an array, the initial value is null and has no size. Below is one simple way of initializing an array:
import java.util.Arrays;
/**
 * A Simple Example that Initialise A Java Array Using Assignment.
 */
public class InitializeJavaArray {
   public static void main(String[] args) {
      int[] testArray = new int[4];
      System.out.println(Arrays.toString(testArray));
      testArray[0] = 2;
      testArray[1] = 3;
      testArray[2] = 5;
      testArray[3] = 7;
      System.out.println(Arrays.toString(testArray));
   }
}
The code new int[4]; creates an array of int with size 4. Hence the variable testArray can hold up to 4 values of int, because we assigned to it the newly created array. We can then assign values to each item of the array. When we run the code, we will get this output:
[0, 0, 0, 0]
[2, 3, 5, 7]

Notice that the first line of output means that the array contains 0 as value to each of it's item. This is because the individual item of the array is un-initialized. And the primitive int has the default value 0. The second line of output reflects the values assigned to the variable items.

Consider the example below:

import java.util.Arrays;
/**
 * A Simple Example that Initialise A Java Array Using Assignment.
 */
public class InitializeJavaArray {
   public static void main(String[] args) {
      String[] testArray = new String[4];
      System.out.println(Arrays.toString(testArray));
      testArray[0] = "Apple";
      testArray[1] = "Banana";
      testArray[2] = "Coconut";
      testArray[3] = "Dewberry";
      System.out.println(Arrays.toString(testArray));
   }
}

The output of the code will be:

[null, null, null, null]
[Apple, Banana, Coconut, Dewberry]

Notice that the first line outputs all nulls. This is because the code new String[4] just creates the array object. Since each item of the array are also objects, they are not yet created and has null value initially. Each item should be assigned a value to avoid having null values.

Declare And Initialize Java Array In One Statement

If the size of the array you wish to initialize is fairly small and you know what values you want to assign, you may declare and initialize an array in one statement. Below shows an example on how to do it in 4 ways:
import java.util.Arrays;
/**
 * A Simple Example that Declares And Initialise A Java Array In One Go.
 */
public class InitializeJavaArray {
   public static void main(String[] args) {
      int[] testArray1 = {1, 2, 3, 4, 5};
      int testArray2[] = {6, 7, 8, 9, 10};
      int[] testArray3 = new int[] {11, 12, 13, 14, 15};
      int testArray4[] = new int[] {16, 17, 18, 19, 20};
      System.out.println(Arrays.toString(testArray1));
      System.out.println(Arrays.toString(testArray2));
      System.out.println(Arrays.toString(testArray3));
      System.out.println(Arrays.toString(testArray4));
   }
}

The code will have the output below when executed:

[1, 2, 3, 4, 5]
[6, 7, 8, 9, 10]
[11, 12, 13, 14, 15]
[16, 17, 18, 19, 20]

Again, this is only practical when the size of array is relatively small.

Initialize Java Array In One Statement

Below is an example if we want to initialize a Java Array in one statement, but separate from the declaration:

import java.util.Arrays;
/**
 * A Simple Example that Declares And Initialise A Java Array Separately.
 */
public class InitializeJavaArray {
   public static void main(String[] args) {
      int[] testArray;
      testArray = new int[] {5, 7, 11, 13, 17};
      System.out.println(Arrays.toString(testArray));
   }
}

Note that this code is valid:

testArray = new int[] {5, 7, 11, 13, 17};

While this code is NOT VALID:

testArray = {5, 7, 11, 13, 17};

Initialize Java Array With Same Value

If we have a large Array and wants to initialize each item with the same value we may use the Arrays utility class to help us. Below is a simple example:

import java.util.Arrays;
/**
 * A Simple Example that Initialise A Java Array With The Same Value.
 */
public class InitializeJavaArray {
   public static void main(String[] args) {
      int[] testArray = new int[10];
      Arrays.fill(testArray, 50);
      System.out.println(Arrays.toString(testArray));
   }
}

The critical code is this:

Arrays.fill(testArray, 50);

Since the value of each item in the array has been initialized with the value of 50, the output of the code will be:

[50, 50, 50, 50, 50, 50, 50, 50, 50, 50]

Initialize Java Array Using Loops

We may use for loops to initialize individual items of an array. Below is a simple example of how to assign the numbers 1 to 10 to an array with 10 values.

import java.util.Arrays;
/**
 * A Simple Example that Initialise A Java Array With Values 1 to 10.
 */
public class InitializeJavaArray {
   public static void main(String[] args) {
      int[] testArray = new int[10];
      for (int i=0; i<10; i++) {
         testArray[i] = i + 1;
      }
      System.out.println(Arrays.toString(testArray));
   }
}

The output of the code will be:

[1, 2, 3, 4, 5, 6, 7, 8, 9, 10]

Below is a simple example that fills an array with the first 10 even numbers.

import java.util.Arrays;
/**
 * A Simple Example that Initialise A Java Array With the first 10 even numbers.
 */
public class InitializeJavaArray {
   public static void main(String[] args) {
      int[] testArray = new int[10];
      for (int i=0; i<10; i++) {
         testArray[i] = (i + 1) * 2;
      }
      System.out.println(Arrays.toString(testArray));
   }
}

Below is the output of the code:

[2, 4, 6, 8, 10, 12, 14, 16, 18, 20]

Below is another example that fills an array with the first 10 prime numbers. The code is a bit long because it is meant to be a more readable algorithm.

import java.util.Arrays;
/**
 * A Simple Example that Initialise A Java Array With the first 10 prime numbers.
 */
public class InitializeJavaArray {
   public static void main(String[] args) {
      int[] testArray = new int[10];
      int prime = 2;
      for (int i = 0; i < 10; i++) {
         boolean primeFound = false;
         do {
            int divisors = 0;
            for (int j = 2; j < prime - 1; j++) {
               if (prime % j == 0) {
                  divisors++;
               }
            }
            if (divisors <= 1) {
               primeFound = true;
            } else {
               prime++;
            }
         } while (!primeFound);
         testArray[i] = prime;
         prime++;
      }
      System.out.println(Arrays.toString(testArray));
   }
}

And the output is below.

[2, 3, 4, 5, 7, 9, 11, 13, 17, 19]

Initialize Java Array From Console

If we need to get the values of an array from the user, below is a simple example on how to initialize a Java Array with values coming from the console:

import java.util.Arrays;
/**
 * A Simple Example that Initialise A Java Array With Values From Console.
 */
public class InitializeJavaArray {
   public static void main(String[] args) {
      int[] testArray = new int[10];
      for (int i = 0; i < 10; i++) {
         String stringValue = System.console().readLine("Enter number: " );
         testArray [ i ] = Integer.parseInt(stringValue);
      }
      System.out.println(Arrays.toString(testArray));
   }
}

This code reads an input from the user via the console:

System.console().readLine("Enter number: " );

And we need to convert the String to an int via:

Integer.parseInt(stringValue);