Declare an empty array in Java
This post will discuss how to declare an empty array in Java.
1. Array Initializer
To create an empty array, you can use an array initializer. The length of the array is equal to the number of items enclosed within the braces of the array initializer. Java allows an empty array initializer, in which case the array is said to be empty.
The following code creates an array of zero length using an empty array initializer. Note that once an array is created, its length never changes. If you’re looking for the resizable arrays, use an ArrayList instead.
|
1 2 3 4 5 6 7 8 9 |
import java.util.Arrays; public class Main { public static void main(String[] args) { int[] arr = {}; System.out.println(Arrays.toString(arr)); } } |
Output:
[]
You can also use an array creation expression to create an empty array.
|
1 2 3 4 5 6 7 8 9 |
import java.util.Arrays; public class Main { public static void main(String[] args) { int[] arr = new int[0]; System.out.println(Arrays.toString(arr)); } } |
Output:
[]
Note that an array initializer may be specified as part of the array creation expression:
|
1 2 3 4 5 6 7 8 9 |
import java.util.Arrays; public class Main { public static void main(String[] args) { int[] arr = new int[] {}; System.out.println(Arrays.toString(arr)); } } |
Output:
[]
2. Create a 2D Array
You can declare a two-dimensional array in Java using a similar syntax. The following code creates a two-dimensional integer array of length 0, whose element is int[].
|
1 2 3 4 5 6 7 8 9 |
import java.util.Arrays; public class Main { public static void main(String[] args) { int[][] arr = new int[0][]; System.out.println(Arrays.deepToString(arr)); } } |
Output:
[]
It is also permissible to create an empty two-dimensional array containing non-empty arrays. For example, the following code creates an empty array of int[1] elements:
|
1 2 3 4 5 6 7 8 9 |
import java.util.Arrays; public class Main { public static void main(String[] args) { int[][] arr = new int[0][1]; System.out.println(Arrays.deepToString(arr)); } } |
Output:
[]
That’s all about declaring an empty array 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 :)