Course – LS – All

Get started with Spring and Spring Boot, through the Learn Spring course:

>> CHECK OUT THE COURSE

1. Overview

In this quick tutorial, we’re going to examine the different ways that we can initialize an array, and the subtle differences between them.

Further reading:

Arrays in Java: A Reference Guide

A simple and complete reference guide to understanding and using Arrays in Java.

Array Operations in Java

Learn how we can handle common array operations in Java.

Java List Initialization in One Line

In this quick tutorial, we'll investigate how can we initialize a List using one-liners.

2. One Element at a Time

Let’s start with a simple, loop-based method:

for (int i = 0; i < array.length; i++) {
    array[i] = i + 2;
}

We’ll also see how we can initialize a multi-dimensional array one element at a time:

for (int i = 0; i < 2; i++) {
    for (int j = 0; j < 5; j++) {
        array[i][j] = j + 1;
    }
}

3. At the Time of Declaration

Now let’s initialize an array at the time of declaration:

String array[] = new String[] { 
  "Toyota", "Mercedes", "BMW", "Volkswagen", "Skoda" };

While instantiating the array, we don’t have to specify its type:

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

Note that it’s not possible to initialize an array after the declaration using this approach; an attempt to do so will result in a compilation error.

4. Using Arrays.fill()

The java.util.Arrays class has several methods named fill(), which accept different types of arguments and fill the whole array with the same value:

long array[] = new long[5];
Arrays.fill(array, 30);

The method also has several alternatives, which set the range of an array to a particular value:

int array[] = new int[5];
Arrays.fill(array, 0, 3, -50);

Note that the method accepts the array, the index of the first element, the number of elements, and the value.

5. Using Arrays.copyOf()

The method Arrays.copyOf() creates a new array by copying another array. The method has many overloads, which accept different types of arguments.

Let’s see a quick example:

int array[] = { 1, 2, 3, 4, 5 };
int[] copy = Arrays.copyOf(array, 5);

A few notes here:

  • The method accepts the source array and the length of the copy to be created.
  • If the length is greater than the length of the array to be copied, then the extra elements will be initialized using their default values.
  • If the source array has not been initialized, then a NullPointerException is thrown.
  • Finally, if the source array length is negative, then a NegativeArraySizeException is thrown.

6. Using Arrays.setAll()

The method Arrays.setAll() sets all elements of an array using a generator function:

int[] array = new int[20];
Arrays.setAll(array, p -> p > 9 ? 0 : p);

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

If the generator function is null, then a NullPointerException is thrown.

7. Using ArrayUtils.clone()

Finally, let’s utilize the ArrayUtils.clone() API out of Apache Commons Lang 3, which initializes an array by creating a direct copy of another array:

char[] array = new char[] {'a', 'b', 'c'};
char[] copy = ArrayUtils.clone(array);

Note that this method is overloaded for all primitive types.

8. Conclusion

In this brief article, we explored different ways of initializing arrays in Java.

As always, the full version of the code is available over on GitHub.

Course – LS – All

Get started with Spring and Spring Boot, through the Learn Spring course:

>> CHECK OUT THE COURSE
res – REST with Spring (eBook) (everywhere)
Comments are open for 30 days after publishing a post. For any issues past this date, use the Contact form on the site.