Declare and initialize arrays in Java
In this post, we’ll see how to declare and initialize arrays in Java.
1. Using new operator
We can declare and initialize arrays in Java by using a new operator with an array initializer. Here’s the syntax:
Type[] arr = new Type[] { comma separated values };
For example, the following code creates a primitive integer array of size 5 using a new operator and array initializer.
|
1 |
int[] arr = new int[] { 1, 2, 3, 4, 5 }; |
Here’s an alternate syntax for declaring an array, where [] appears after the variable name, similar to C/C++ style arrays.
Type[] arr = new Type[] { comma separated values };
2. Splitting declaration and initialization
Here is how we can split the declaration and initialization of the array.
Type[] arr;
arr = new Type[] { comma separated values };
The first line depicts the array declaration, and the second line represents the array initialization. For example,
|
1 2 |
int[] arr; arr = new int[] { 1, 2, 3, 4, 5 }; |
3. Shortcut syntax with array initializer
We can also declare and initialize arrays in a single line without using a new operator, as shown below:
Type[] arr = { comma separated values };
Here’s the code:
|
1 |
int[] arr = { 1, 2, 3, 4, 5 }; |
4. Using default values in initialization of array
If we don’t provide any initializer, the default value of 0 is assigned to each element in the case of short or int or long or byte array. For double or float, the default value is 0.0, and the default value is null for string.
Type[] arr = new Type[capacity];
For example, the following code creates a primitive integer array of size 5. The array will be auto-initialized with a default value of 0.
|
1 2 |
int[] arr = new int[5]; System.out.println(Arrays.toString(arr)); // [0, 0, 0, 0, 0] |
We can use the Arrays.fill() method to assign a specified value to each element of the specified array. For example, the following code creates an array of 5 ints and assigns each element with a value of 1.
|
1 2 3 |
int[] arr = new int[5]; Arrays.fill(arr, 1); System.out.println(Arrays.toString(arr)); // [1, 1, 1, 1, 1] |
Arrays.fill() also has an overloaded version that can be used to assign a value to each element of the specified range of the array.
|
1 2 3 4 5 6 |
int[] arr = new int[5]; // fill value 1 from index 0, inclusive, to index 3, exclusive Arrays.fill(arr, 0, 3, 1); System.out.println(Arrays.toString(arr)); // [1, 1, 1, 0, 0] |
Java 8 introduced several enhancements to the Arrays class, like introduction of Arrays.setAll() method. We can use it to set all elements of the specified array, using the generator method that computes the desired value for every index.
For example, the following code creates an array of 5 ints and sets all of its elements to their respective index value:
|
1 2 3 |
int[] arr = new int[5]; Arrays.setAll(arr, i -> i); System.out.println(Arrays.toString(arr)); // [0, 1, 2, 3, 4] |
5. Using Reflection
We can declare and initialize arrays with reflection, using the following syntax:
Type[] arr = (Type[]) Array.newInstance(Type.class, capacity);
It creates a new array with the specified type and length with a default value of 0. Here’s how we can create a primitive integer array of length 5:
|
1 |
int[] arr = (int[]) Array.newInstance(int.class, 5); |
6. Using IntStream
In Java 8, we can use IntStream.rangeClosed() to generate a sequential ordered IntStream between two specified indexes.
For example, IntStream.rangeClosed(1, 5) will generate a sequence of increasing values from 1 to 5 by an incremental step of 1. To get a primitive integer array, we can call toArray() method on IntStream, as shown below:
|
1 |
int[] arr = IntStream.rangeClosed(1, 5).toArray(); |
We can also use IntStream.range(start, end) that generate a sequence of increasing values from start to end (exclusive).
|
1 |
int[] arr = IntStream.range(1, 6).toArray(); |
Few points to remember
int[] a, b;is not the same asint a[], b;- The array’s size is fixed and cannot be modified after the array is created. The length field in an array is final and stores the size of an array.
- If we need a resizable-array implementation, we should use an
ArrayList. As elements are added to anArrayList, it grows automatically. - If an array index is either negative or greater than or equal to the array’s size, an
ArrayIndexOutOfBoundsExceptionis thrown to indicate that an array has been accessed with an illegal index. To avoid it, we can check that the index is within the limits of the array. - Java also allows to have arrays of size
0, as shown below:12int[] arr = new int[0];System.out.println(Arrays.toString(arr)); // prints []or
12int[] arr = {};System.out.println(Arrays.toString(arr)); // prints []
Since it’s an empty array, it throws anArrayIndexOutOfBoundsExceptionif we try to read elements from it or assign elements to it. - A
NegativeArraySizeExceptionwill be thrown if a program tries to create an array with a negative size. For example,1int[] arr = new int[-5];
That’s all about declaring and initializing arrays in Java.
Thanks for reading.
To share your code in the comments, please use our online compiler that supports C, C++, Java, Python, JavaScript, C#, PHP, and many more popular programming languages.
Like us? Refer us to your friends and support our growth. Happy coding :)