How to Initializing Array in Java

In this post, we will cover different options for Initializing Array in Java along with main differences with each option.

 

Initializing Array in Java

Array is a collection of same data types. It’s one of the  fundamental data structure of Java and most of the collection framework internally rely on this data structure.In this post, we will be covering some of the commonly used ways for Initializing Array in Java, we will also discuss briefly these different options and subtle differences between them.

 

1. Initializing Array in Java using Loop

One of the simplest ways is to initialize an array using a loop, this method will fill one element at a time in the Array.We can use this technique to even initialize multi-dimensional array

for( int i=0; i< length ; i++){
    data[i] = i;
}
//multi dimensional arrays init
for( int i=0; i< length ; i++){
  for( int j=0; j< 10h ; j++){
    data[i][j] = i;
  }
}

 

2. Initializing Array During Declaration

If we know about the size and element of the array, we can also initialize it at the declaration time.This is less common used technique until we are very sure about the array size.

int[] data = {101,201,130,401,350,660,771,880,890,891};

int[] data;
data = new int[] {100,200,300,400,500,600,710,800,900,912};

String[] strings = new String[] {"Sunday", "Monday","Tuesday"};

Please be aware the with above syntax, you will not be able to initialize after this, the system will be throwing a compile-time error if we will try to do this.

 

3. Arrays.fill()

Arrays class contains various methods for manipulating arrays, we can use any of the Arrays.fill() method to fill given the array with the same value.

long array[] = new long[15];
Arrays.fill(array, 20);

There are multiple variations of the fill method which can be used based on the requirement.One of the other variation is to initialize the array using a range.Here is how to do this:

int[] array = new int[3];
/**
 * Assigns the specified int value to each element of the specified
 * range of the specified array of ints.  The range to be filled
 * extends from index <tt>fromIndex</tt>, inclusive, to index
 * <tt>toIndex</tt>, exclusive.  (If <tt>fromIndex==toIndex</tt>, the
 * range to be filled is empty.)
 *
 * @param array the array to be filled
 * @param fromIndex the index of the first element (inclusive) to be
 *        filled with the specified value
 * @param toIndex the index of the last element (exclusive) to be
 *        filled with the specified value
 * @param val the value to be stored in all elements of the array
 * @throws IllegalArgumentException if <tt>fromIndex > toIndex</tt>
 * @throws ArrayIndexOutOfBoundsException if <tt>fromIndex < 0</tt> or
 *         <tt>toIndex > a.length</tt>
 */
Arrays.fill(array, 0, 2, 10);
for (int i = 0; i < array.length; i++) {
    System.out.println(array[i]); // 10, 10
}

Arrays.fill(array, 0, 4, 10); //throws java.lang.ArrayIndexOutOfBoundsException

We can use the Arrays.fill() method to initialize String or other types of array object as well.

 

4. Arrays.setAll()

These methods set all elements of the specified array, using the provided generator function to compute each element.

int[] arr = new int[10];
Arrays.setAll(arr, (index) -> 1 + index);

 

5. Initializing Array Using Java 8

Java 8 came up with lots of new feature. You can use the Java 8 stream API to initialize a given array.You can use the IntStream to create a continuous stream of integers from 0 inclusive to n exclusive.Let’s take a look at some of the examples:

int[] tempArray = IntStream.range(0, 5).toArray(); // 0 to 4
int[] closeRangeArray = IntStream.rangeClosed(0, 4).toArray(); // from o to 4 inclusive
int[] sortedArray = IntStream.of(10, 34, 1, 4).sorted().toArray(); // 1,4,10,34

If your requirement is simple, I will still recommend to use the simple for-loop to initialize the array.

 

Summary

In this short post, we covered different options to Initializing Array in Java.We discussed initializing array using simple for loop and also using the new Java 8 stream API.These are handy techniques and commonly used in the day to day development. To summarize, if we have a simple requirement, we should reply on the good old for loop.You can always get the source code for out GitHub repository.

Scroll to Top