Initializing an array means populating it with elements or adding some values to it.
There are many different ways to initialize an array in java and this article will cover many of them.
1. At declaration time
Provide elements at the time of declaring it by providing their values in curly braces. Example,
int[] arr = {1,2,3,4,5};
This way, we don’t need to provide the size as the compiler infers it from the count of elements provided.
If you know array elements at the time of its creation, then use this approach as it is concise.
2. Loop
Declare an array and add elements to it inside a loop that executes till the size of array.
In every loop iteration, assign a value to array index one by one as below
int[] arr = new int[5]; for (int i = 0; i < 5; i++) { arr[i] = i; }
With this approach, you need to declare the array first and then assign values to it.
Use this approach when you do not know array elements at the time of its creation.
Also, be careful with the loop count as it should execute till the max array index else you will get ArrayIndexOutOfBoundsException.
3. Java stream
Java 8 introduced streams which are a sequence of elements.
You can use a stream to generate elements similar to a for loop in above example.
IntStream stream = IntStream.range(0, 6); int[] array = stream.toArray(); System.out.println(Arrays.toString(array));
IntStream
has a range()
method which accepts two integers and returns a stream from first argument inclusive and second excluded.toArray()
method of this stream converts this stream to an array of elements.
You can print the array using Arrays.toString()
.
4. Arrays.fill()
If you want to initialize array with same values, then Arrays.fill()
is the perfect method.fill()
accepts the array and the value to be populated as arguments. Example,
int arr[] = new int[5]; Arrays.fill(arr, 5); System.out.println(Arrays.toString(arr)); // will be [5,5,5,5,5]
fill()
has an overloaded method that can be used to populate specified index of the array.
It takes 4 arguments:
a. the array,
b. start index,
c. end index,
d. value
Keep caution about the indexes such as start index should be greater and 0, end index should be lesser than the length of array, start index should be lesser than the end index or else you will get ArrayIndexOutOfBoundsException
.
5. Arrays.copyOf()
copyOf()
method accepts an array and the size and creates a new array of given size with elements copied from the first array. Example,
int arr[] = {1,2,3,4,5}; int[] copy = Arrays.copyOf(arr, 5); System.out.println(Arrays.toString(copy)); // copy array => {1,2,3,4,5}
If the size argument is greater than the length of source array, then the remaining elements will be initialized to default values of array data type.
So, in above example, if the size is 10, then the copy array will be
{1,2,3,4,5,0,0,0,0,0}
6. Arrays.setAll()
setAll()
method was added in java 8 and is used to set values of an array based on a generator function.
It takes two arguments, the array to populate and a generator function which is an object of type IntUnaryOperator
.
IntUnaryOperator
is a functional interface with a single abstract method applyAsInt().
It accepts one argument and returns a value.
setAll()
is called for each array element and its index is provided to the generator function.
So, you can generate the values as per a pattern.
Also, IntUnaryOperator
is a functional interface and so it can be represented as a lambda expression.
Example, below code generates array values as cubes of indexes.
int arr[] = {1,2,3,4,5}; Arrays.setAll(arr, i -> i * i * i); System.out.println(Arrays.toString(arr)); // array will be [0,1,8,27
That is all on different ways to initialize an array in java.
Hope the article was useful.