Javatpoint Logo
Javatpoint Logo

Empty Array in Java

An array that either has no elements or all of its elements are null is referred to as an empty array in Java. The new keyword in Java can be used to declare an empty array. An array that is empty or has no elements is referred to as a zero-length array in Java. In Java, an array has to satisfy one of the conditions that follows in order to be considered empty:

  • It should be empty, meaning that the array's size should be zero.
  • It should only contain empty items.

Initializing of an Empty Array:

The method of assigning values by declaring an array of a particular size without providing it any values is known as empty array initialization. If the array is not initialised with any data, it will by default contain random values, often known as garbage values.

Java requires that we use the new keyword followed by the data type of the elements the array would store in order to initialise an empty array. This array will have a size of 0.

Syntax:

Implementation:

FileName: EmptyArray.java

Output:

[]

There are different ways to check whether an array is Empty. They are as follows:

  1. Using Null Check
  2. Using Length Property
  3. Using Null Check on Elements

Approach: Using Null Check

In this, we will learn by using the null property we determine whether an array is empty or not. If an array shows the value NULL, it might be considered to be empty in Java.

Implementation:

FileName: NullCheck.java

Output:

The array is an Empty Array

Approach: Using Length Property

In this, we will learn by using the Length property we determine whether an array is empty or not. If an array is empty or not, its length can be used to determine this. An array is empty if its length is 0, which happens to be the case in the majority of instances.

Implementation:

FileName: LengthProperty.java

Output:

The array is an Empty Array

Approach: Using Null Check on Elements

If every element in an array is null, the array is said to be empty in Java. In order to determine whether the array is empty or not, we shall traverse over it. If we find a non-null element, then the array is not empty.

Implementation:

FileName: NullElements.java

Output:

The array is an empty array






Youtube For Videos Join Our Youtube Channel: Join Now

Feedback


Help Others, Please Share

facebook twitter pinterest

Learn Latest Tutorials


Preparation


Trending Technologies


B.Tech / MCA