Java – Initialize Array
You can initialize array in Java using new keyword and size or by directly initializing the array with list of values. We will look into these tow different ways of initializing array with examples.
Initialize Array using new keyword
You can initialize an array using new keyword and specifying the size of array.
Following is the syntax to initialize an array of specific datatype with new keyword and array size.
datatype arrayName[] = new datatype[size];
where
datatype
specifies the datatype of elements in array.arrayName
is the name given to array.new
keyword creates the array and allocates space in memory.size
specifies the number of elements in the array.
In the following example program, we will create an integer array of size five.
Java Program
public class ArrayExample {
public static void main(String[] args) {
int numbers[] = new int[5];
}
}
By default, the elements are initialized to default value of the datatype, which in this case of integer, it is zero. Let us check this statement by printing the elements of array.
Java Program
public class ArrayExample {
public static void main(String[] args) {
int numbers[] = new int[5];
for(int number: numbers)
System.out.println(number);
}
}
Output
0
0
0
0
0
You can override these elements of array by assigning them with new values.
In the following program, we will initialize the array and assign values to its elements. You can access array elements using index.
Java Program
public class ArrayExample {
public static void main(String[] args) {
int numbers[] = new int[5];
numbers[0] = 42;
numbers[1] = 25;
numbers[2] = 17;
numbers[3] = 63;
numbers[4] = 90;
for(int number: numbers)
System.out.println(number);
}
}
Output
42
25
17
63
90
Initialize Array with List of Values
Instead of using new keyword, you can also initialize an array with values while declaring the array.
Following is the syntax of initializing an array with values.
datatype arrayName[] = {element1, element2, element3, ...}
Let us write a Java program, that initializes an array with specified list of values.
Java Program
public class ArrayExample {
public static void main(String[] args) {
int numbers[] = {42, 25, 17, 63, 90};
for(int number: numbers)
System.out.println(number);
}
}
Output
42
25
17
63
90
Conclusion
In this Java Tutorial, we learned different ways of how to initialize an array with elements.