Return Empty Array in JAVA

You are currently viewing Return Empty Array in JAVA

In this tutorial, I am going to teach “How to return empty array in JAVA” using three ways. Okay, let’s move on to the article.

Return an Empty Array Using new int[0] in Java

public class EmptyArray {
    public static void main(String[] args) {

        int[] getEmptyArray = returnEmptyArray();

        System.out.println(getEmptyArray.length);
    }

    private static int[] returnEmptyArray() {
        return new int[0];
    }
}

Output:

0

Return an Empty Array Using Empty Curly Braces in Java

public class EmptyArray {
    public static void main(String[] args) {

        int[] getEmptyArray = returnEmptyArray();

        System.out.println(getEmptyArray.length);
    }

    private static int[] returnEmptyArray() {

        int[] emptyArr = {};

        return emptyArr;
    }
}

Output:

0

Read also:- How to Check If a String Contains a Character in JAVA

Return an Empty Array Using “org.apache.commons.lang3.ArrayUtils”

In this example, we are going to use “ArrayUtils” which is a class of Apache Commons Library. We have to import using the following code.

 <dependency>
    <groupId>org.apache.commons</groupId>
    <artifactId>commons-lang3</artifactId>
    <version>3.11</version>
 </dependency>
import org.apache.commons.lang3.ArrayUtils;

public class EmptyArray {
    public static void main(String[] args) {

        String[] getEmptyArray = returnEmptyArray();

        System.out.println(getEmptyArray.length);
    }

    private static String[] returnEmptyArray() {

        return ArrayUtils.EMPTY_STRING_ARRAY;
    }
}

Output:

0

Final Words

I hope this article helps you to Return Empty Array in JAVA. If you face any issues please let me know via the comment section. Share this article with other JAVA developers via social networks.

Ranjith

Hi, I'm Manoj a full-time Blogger, YouTuber, Affiliate Marketer, & founder of Coding Diksha. Here, I post about programming to help developers.

Leave a Reply