Initialize Empty Array in Java

Initialize empty array in java

💡 Outline
You can use below code to initialize empty array in java.

Or

Or

1. Introduction

In this post, we take a look on How to Initialize empty array in Java. We will look at different ways to Initialize arrays in Java with dummy values or with prompted user inputs. Arrays in Java follow a different declaration paradigm than other programming languages like C, C++, Python, etc.

In Java, array is by default regarded as an object and they are allocated memory dynamically. Moreover, in java at the time of creation an array is initialized with a default value. For Example: If the array is of type int(integer) all the elements will have the default value 0.

Hence, we will outline different methods to initialize an empty array with examples, to make it easy for a beginner in Java to use appropriate example under apt cases.

2. Initialize an empty array in Java

Considering all cases a user must face, these are the different methods to initialize an array:

Let us look at these methods in detail.

2.1 Using Array Initializer

To declare empty array, we can use empty array initializer with {}. Java

Here is sample program:

Length of the array will be number of elements enclosed in {}. Since we have put nothing in {}, length of Array will be 0.

Please note that once you create empty array, you can’t change the length. In case, you need to change the size, you should use ArrayList instead.

You can also initialize empty array with Array creation expression as below:

2.2 Using new keyword with 0 size

You can use new keyword with 0 size.

3. Initialize empty 2D Array in Java

You can initialize empty 2D array similar to empty Array.

We can also create empty 2D array of non empty Arrays.

As Java allows to create empty array with size 0 for int and String.

Similarly it allows empty of int[1] here.

That’s all about how to initialize empty array in Java.

Was this post helpful?

Leave a Reply

Your email address will not be published. Required fields are marked *