Create empty array in java – Code Example

To create an empty array in java, you can use = {} syntax or = new int[0]. But an empty array is useless because it can’t hold any value. If you need a dynamic array whose size is not defined and could hold any number of items, then you should use ArrayList.

Code Example –

1 – Empty array using ={}

int myArray[] = {};

It’s a integer array with no scope of holding any value.


2 – Empty array using = new int[0]

int myArray[] = new int[0];

This array is also empty and can not hold any value.


3 – Empty array but can hold given number of items –

int myArr[] = new int[6];

It’s empty but can hold 6 items.


4 – Empty array which can hold any number of elements –

ArrayList<String> heroes = new ArrayList<String>();

heroes.add("Ironman");
heroes.add("Captain America");

heroes.get(0); // Output: Ironman