Initializing Arrays in Java
An array is a linear data structure used to store similar elements in an ordered fashion. An array is a very simple but powerful data structure that can be used for a variety of tasks. Each element stored in the array can be accessed by using its index value. Arrays follow zero-based indexing, which means that the first index will be zero. In this tutorial, we will learn the different ways to initialize an array in Java.
Declaring An Array in Java
Before initializing, we must know how to declare an array. Declaring means defining the variable name and the data type of the elements that will be stored in the array. The general syntax of declaring an array is shown by the code below.
datatype[] variableName;
Initializing An Array in Java
Let's learn the different ways in which we can assign values to an array.
Initializing All Array Elements to Zero
We can simply declare an array and initialize each element of the array to zero in just a single line of code. Zero is the default value that Java assigns when we declare the size of the array. The following code demonstrates this scenario.
public class InitializeDemo
{
public static void main(String[] args)
{
//Declaring array
int[] intArray;
//Initializing to Zero
intArray = new int[5];
//Printing the values
for(int i = 0; i < intArray.length; i++)
System.out.println(intArray[i]);
}
}
0
0
0
0
0
For a string array, the default value is null.
public class InitializeDemo
{
public static void main(String[] args)
{
//Declaring array
String[] strArray;
//Initializing to Zero
strArray = new String[5];
//Printing the values
for(int i = 0; i < strArray.length; i++)
System.out.println(strArray[i]);
}
}
null
null
null
null
null
Initializing Array Elements One at a Time
We don't always want to store zeroes in an array. We can initialize each element one by one with the help of a single for loop. We will use the indices of the elements to initialize the array.
For example, let's initialize an array to store the squares of the first 5 natural numbers.
public class InitializeDemo
{
public static void main(String[] args)
{
//Declaring array
int[] intArray;
//Defining the array length
intArray = new int[5];
//Initializing
for(int i = 0; i < intArray.length; i++)
intArray[i] = (i+1) * (i+1);
//Printing the values
for(int i = 0; i < intArray.length; i++)
System.out.println(intArray[i]);
}
}
1
4
9
16
25
If we are working with multidimensional arrays then we need to use nested loops. The following code shows how to initialize a 2D array.
public class InitializeDemo
{
public static void main(String[] args)
{
//Declaring array
int[][] intArray;
//Defining the array length
intArray = new int[3][4];
//Initializing
for(int i = 0; i < intArray.length; i++)
for(int j = 0; j < intArray[0].length; j++)
intArray[i][j] = (i+1) * (j+1);
//Printing the values
for(int i = 0; i < intArray.length; i++)
{
for(int j = 0; j < intArray[0].length; j++)
System.out.print(intArray[i][j] + " ");
System.out.println();
}
}
}
1 2 3 4
2 4 6 8
3 6 9 12
We can also take user input to initialize an array by using the Scanner class.
import java.util.Scanner;
public class InitializeDemo
{
public static void main(String[] args)
{
//Declaring array
int[] intArray;
//Defining the array length
intArray = new int[5];
Scanner s = new Scanner(System.in);
System.out.println("Enter the values: ");
//Initializing
for(int i = 0; i < intArray.length; i++)
intArray[i] = s.nextInt();
s.close();
System.out.println("The array contains: ");
//Printing the values
for(int i = 0; i < intArray.length; i++)
System.out.println(intArray[i]);
}
}
Enter the values:
5
10
15
20
25
The array contains:
5
10
15
20
25
Initializing an Array at the time Declaration
We can declare an array and also initialize it at the same time with just a single line of code. We do not need to specify the size of the array when using this technique to initialize.
public class InitializeDemo
{
public static void main(String[] args)
{
//Declaring array
int[] intArray = {3,6,9,12,15};
//Printing the values
for(int i = 0; i < intArray.length; i++)
System.out.println(intArray[i]);
}
}
3
6
9
12
15
Using Arrays.fill() Method
The Arrays class provides us with the fill() method that can be used to fill an entire array or a part of the array with some elements. This method cannot initialize an array and it is used to modify an already initialized array.
If we use the following signature then all elements of the array will be set to the value parameter.
public static void fill(int[] intArray, int value)
Instead, if we use the following syntax then all elements between the fromIndex and toIndex(exclusive) will be set to the value parameter.
public static void fill(int[] intArray, int fromIndex, int toIndex, int value)
The following code demonstrates the working of the fill() method. We can use arrays of other data types as well.
import java.util.Arrays;
public class InitializeDemo
{
public static void main(String[] args)
{
int[] intArray = new int[10]; //Array initialized with zeroes.
System.out.println("Initial Array: " + Arrays.toString(intArray));
Arrays.fill(intArray, -5);//Changing all the elements to -5
System.out.println("Changing all elements of the array: " + Arrays.toString(intArray));
int fromIdx = 1, toIdx = 5;
Arrays.fill(intArray, fromIdx, toIdx, 0);//Changing some elements back to 0
System.out.println("Changing a few elements of the array: " + Arrays.toString(intArray));
}
}
Initial Array: [0, 0, 0, 0, 0, 0, 0, 0, 0, 0]
Changing all elements of the array: [-5, -5, -5, -5, -5, -5, -5, -5, -5, -5]
Changing a few elements of the array: [-5, 0, 0, 0, 0, -5, -5, -5, -5, -5]
Using Arrays.setAll() Method
The setAll() method of the Arrays class can be used to initialize an array with the help of a Generator Function. This generator function computes the array values by using the index.
For example, let's try to initialize an array with squares of the first 10 natural numbers.
import java.util.Arrays;
public class InitializeDemo
{
public static void main(String[] args)
{
//Declaring array
int[] intArray;
intArray = new int[10];
//Initializing using setAll()
Arrays.setAll(intArray, (index) -> (index+1) * (index+1) );
//Printing the values
for(int i = 0; i < intArray.length; i++)
System.out.println(intArray[i]);
}
}
1
4
9
16
25
36
49
64
81
100
Now, let's try initializing a string array. If the index of an element is less than 5 then it should have the value < 5, else it should have the value >=5.
import java.util.Arrays;
public class InitializeDemo
{
public static void main(String[] args)
{
//Declaring array
String[] strArray;
strArray = new String[10];
//Initializing using setAll()
Arrays.setAll(strArray, (index) -> ((index < 5) ? "<5" : ">=5" ));
//Printing the values
for(int i = 0; i < strArray.length; i++)
System.out.println("Index: " + i + " Value: " + strArray[i]);
}
}
Index: 0 Value: <5
Index: 1 Value: <5
Index: 2 Value: <5
Index: 3 Value: <5
Index: 4 Value: <5
Index: 5 Value: >=5
Index: 6 Value: >=5
Index: 7 Value: >=5
Index: 8 Value: >=5
Index: 9 Value: >=5
Using ArrayUtils.clone() Method
We can use the clone() method to initialize an array by copying or cloning another array. This is simply used to create a copy of an existing array. It is part of the Apache Commons Lang 3 package.
import org.apache.commons.lang3.ArrayUtils;
public class InitializeDemo
{
public static void main(String[] args)
{
int[] intArray = {1, 3, 5, 7, 9};
int[] copy = ArrayUtils.clone(intArray);
for(int i = 0; i < copy.length; i++)
System.out.println(copy[i]);
}
}
1
3
5
7
9
Using Arrays.copyOf() Method
We can also use the copyOf() method of the Arrays class to create a copy of another array.
This method takes an additional integer parameter to denote the number of elements to copy.
- If this parameter is less than the length of the original array then only the first few elements will be copied.
- If it is greater than the length of the original array then the additional elements will be initialized to zero.
- If it is exactly equal to the length of the original array then an exact copy is created.
import java.util.Arrays;
public class InitializeDemo
{
public static void main(String[] args)
{
int[] intArray = {1, 3, 5, 7, 9};
int[] copy1 = Arrays.copyOf(intArray, 3);
int[] copy2 = Arrays.copyOf(intArray, 7);
int[] copy3 = Arrays.copyOf(intArray, 5);
System.out.println("Original Array: " + Arrays.toString(intArray));
System.out.println("Copied array with smaller length: " + Arrays.toString(copy1));
System.out.println("Copied array with greater length: " + Arrays.toString(copy2));
System.out.println("Copied array with same length: " + Arrays.toString(copy3));
}
}
Original Array: [1, 3, 5, 7, 9]
Copied array with smaller length: [1, 3, 5]
Copied array with greater length: [1, 3, 5, 7, 9, 0, 0]
Copied array with same length: [1, 3, 5, 7, 9]
Frequently Asked Questions
Q. What is the difference between initializing and declaring an array?
Declaring means to set the name and data type of the elements that will be stored in the array. Initializing means setting an initial value to the array elements.
Q. What is a Dynamic Array?
A Dynamic Array is an array that can be resized dynamically. Normal arrays are of fixed size and we can't insert additional elements in them if they are full but a dynamic array does not have this issue.
Q. How to initialize all elements of an integer array to 0?
As discussed above, if we allocate space to an array then, by default, all the array elements are set to 0. We can also use other methods like fill() and setAll() to do this.
Summary
An array is one of the most frequently used linear data structures. There are a lot of ways of initializing an array in Java. Mostly, we will use the for loop to initialize the elements of the array but one must know the different methods that can also be used for initializing. We also learned how to copy the content of an existing array into a new array by using the clone() and copyOf() methods.