Initialize Arrays in Java

When it comes to initializing arrays in Java, there are several ways to do it. In this article, we will explore some of the most common ways to initialize arrays in Java.

Initializing an Array with values

One of the most common ways to initialize an array in Java is by specifying its values. This can be done using either an array literal or a loop.

1. Using an Array literal

An array literal is a shorthand way of creating an array with values. To use an array literal, we simply enclose the values in curly braces and separate them with commas:

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

or for strings:

java
String[] fruits = {"Apple", "Banana", "Orange"};

2. Using a Loop

When we create a new array in Java, all its elements are initialized with default values. For example, if we create a new array of integers, all its elements will be initialized to zero.

Another way to initialize an array with values is by using a loop. This is useful when we want to initialize an array with a large number of values or when we want to generate the values dynamically.

java
int[] numbers = new int[5];
for (int i = 0; i < numbers.length; i++) {
numbers[i] = i + 1;
}

3. Initializing an array with a range of values

IntStream.range() is a method in Java that returns a sequential ordered IntStream from the first argument (inclusive) to the second argument (exclusive). For example, IntStream.range(1, 6) will return an IntStream containing the values 1, 2, 3, 4, 5.

java
int[] numbers = IntStream.range(1, 6).toArray();

This will create an array containing the values 1, 2, 3, 4, 5.

4. Initializing an array with random values

This will create an array containing five random values between 0 and 9:

java
int[] numbers = new Random().ints(5, 0, 10).toArray();

The first argument 5 specifies the number of values to generate, and the second and third arguments (0 and 10) specify the range of values to generate (inclusive of the lower bound and exclusive of the upper bound).

4. Initializing an array with a single value using Arrays.fill:

Arrays.fill() is a method in Java that fills an array with a given value. The first argument is the array to fill, and the second argument is the value to fill it with.

java
int[] numbers = new int[5];
Arrays.fill(numbers, 42);

This will create an array containing five values of 42.

5. Initializing an array with a IntStream.of()

IntStream.of() is a method in Java that returns an ordered stream of int values. The arguments to IntStream.of() are the values to include in the stream.

java
int[] numbers = IntStream.of(1, 2, 3, 4, 5).toArray();

This will create an array containing the values [1, 2, 3, 4, 5].

6. Initializing an array with a Arrays.copyOf()

Arrays.copyOf() is a method in Java that creates a new array with the specified length and copies the contents of the original array into it. The first argument is the original array, and the second argument is the length of the new array.

Here's an example of how to use Arrays.copyOf() to create a new array with the contents of an existing array:

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

This will create a new array copy containing the values [1, 2, 3, 4, 5].

6. Initializing an array with a Arrays.setAll()

Arrays.setAll() is a method in Java that sets each element of an array to the result of a function applied to its index. The first argument is the array to set, and the second argument is a function that takes an index and returns the value to set at that index.

Here's an example of how to use Arrays.setAll() to set each element of an array to its index:

java
int[] numbers = new int[5];
Arrays.setAll(numbers, i -> i);

This will create an array containing the values [0, 1, 2, 3, 4].

6. Initializing an array with a ArrayUtils.clone()

ArrayUtils.clone() is a method in Apache Commons Lang that creates a new array with the same contents as the original array.

You will need the Apache Commons Lang library to use this method:

XML
<dependency>
<groupId>org.apache.commons</groupId>
<artifactId>commons-lang3</artifactId>
<version>3.12.0</version>
</dependency>

The argument to ArrayUtils.clone() is the original array.

Here's an example of how to use ArrayUtils.clone() to create a new array with the contents of an existing array:

java
int[] numbers = {1, 2, 3, 4, 5};
int[] copy = ArrayUtils.clone(numbers);

This will create a new array copy containing the values [1, 2, 3, 4, 5].

7. Initializing arrays with dynamic values

So far, we have covered static initialization techniques where the array size and values are known in advance. However, in real-world scenarios, you may encounter situations where you need to initialize arrays dynamically at runtime.

You can initialize an array by taking input from the user during runtime. Here's an example:

java
import java.util.Scanner;
// Create a Scanner object
Scanner scanner = new Scanner(System.in);
// Get the size of the array from the user
System.out.print("Enter the size of the array: ");
int size = scanner.nextInt();
// Declare and initialize the array with user input
int[] numbers = new int[size];
for (int i = 0; i < size; i++) {
System.out.print("Enter element " + (i + 1) + ": ");
numbers[i] = scanner.nextInt();
}
// Close the scanner
scanner.close();

In the above example, we used the Scanner class to obtain the size of the array from the user. Then, we initialized the array with user-provided values using a loop.

Author Image
About the author

Gustavo Santos

Gustavo is the founder of DocsFold, based in Portugal. He has worked as a software developer for over 15 years. He enjoys exploring new technologies and using them to automate work as much as possible.