Table of Contents
TL;DR
To return empty Array in Java, you can use curly braces.
1234567 public static String[] returnEmptyStringArray() {String[] emptyArray = {};return emptyArray;}or
12345 public static String[] returnEmptyStringArray() {return new String[]{};}
1. Introduction
In this article, we will take a look on to How to return Empty array in java
. We will look at different ways to achieve this with demonstrated working examples in detail. At first, let us have a brief look into Arrays in java and what exactly is an Empty Array and how it is different from a null array.
An Array is a collection of homogenous or similar type of elements having contiguous memory allocation in a sequence. In Java, arrays are objects which are allocated memory dynamically. We can use arrays to store primitive data(int, float, double etc.) and object types as well.
2. What Is the Need to Return an Empty Array?
An Empty Array is an array with length 0 i.e. it has no elements. This indicates the array along with its reference exists in the memory but has no data within. We declare an empty array as:
1 2 3 |
int arr[] = new int[0]; |
There are certain cases where we need to return an empty array as specified below:
- Suppose the array is coming from an API, and it returns null; in this case, we might want to return an array without any element, instead of null because it will be known what type of an array is actually returned as null doesn’t correspond to primitive type data.
- ReturningÂ
null
instead of an actual array, collection or map forces the callers of the method to explicitly test for its nullity, making the method more complex and less readable.
Example:
1 2 3 4 5 |
public static Result[] getResults() { return null; // Noncompliant } |
Hence, if we return array like this, it will be mandatory to check for nullity in order to avoid NullPointerException in java and this is a recommended coding practice as well. So at the calling end we need to do check like this:
1 2 3 4 5 6 7 8 9 |
public static void main(String[] args) { Result[] results = getResults(); if (results != null) { // Nullity test for (Result result: results) { /* your code */ } } |
3. How Do You Return Empty Array in Java?
There can be 4 methods mentioned in number point as below:
- Return using Curly Braces
- Return using Anonymous Array objects – new int[0] functionÂ
- Return using Empty Array declaration
- Return using Apache Commons – org.apache.commons.lang3.ArrayUtils Package.
In Java, we instantiate an array using { }
with the values added manually or hardcoded, and the array size is the number of elements in the array. It is allowed in Java to return an array with empty curly braces; without any elements the array size will be zero.
We can create a method returnEmptyArray
that returns a
3.1 Using Curly Braces
n array. We initialize an empty array using emptyArray = {}
 and then return emptyArray
. Let us look at the example code.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 |
package org.arpit.java2blog.generic; public class ReturnEmptyArrayMain { public static void main(String args[]) { ReturnEmptyArrayMain ream=new ReturnEmptyArrayMain(); int[] intEmptyArray = ream.returnEmptyIntegerArray(); String[] stringEmptyArray = ream.returnEmptyStringArray(); System.out.println("Integer Array length: "+intEmptyArray.length); System.out.println("String Array length: "+stringEmptyArray.length); } public static int[] returnEmptyIntegerArray() { return new int[] {}; } public static String[] returnEmptyStringArray() { String[] emptyArray = {}; return emptyArray; } } |
Output:
3.2 Using Anonymous Array Objects – New Int[0]Â
In Java, an array has a fixed size that we can specify while creating the array. If the array has a length or size of zero, it indicates it has no values. Hence, we return empty arrays, creating them with a zero size or return an anonymous array without the name declaration. we use the new keyword here to create array and allocate memory to it.
Note: A null array is not an empty array.
We can create an array or just return this value : new int[0]
 that is an empty array of int
. Let us take a look at the example code.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 |
public class ReturnEmptyArrayMain { public static void main(String args[]) { ReturnEmptyArrayMain ream=new ReturnEmptyArrayMain(); int[] intEmptyArray = ream.returnEmptyIntegerArray(); String[] stringEmptyArray = ream.returnEmptyStringArray(); System.out.println("Integer Array length: "+intEmptyArray.length); System.out.println("String Array length: "+stringEmptyArray.length); } public int[] returnEmptyIntegerArray() { // Declaring Array and allocating memory int[] emptyArray = new int[0]; return emptyArray; } public String[] returnEmptyStringArray() { // Return Anonymous Array block return new String[0]; } } |
Output:
3.3 Using Empty Array Declaration
This is another alternative way to declare an empty array with no dimensions i.e. size and then return it. We declare the array array using the conventional way of creating an array and instantiating with the new keyword but we do not input the size in the square brackets []
.
We can return the array like this: new int[]{}
i.e. an integer array or declare first. This is a simpler method to follow the above approach. We will create an empty array of objects of class Employee and then return it.
Let us take a look at the example code.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 |
class Employee { int id; String name; } public class Java2Blog { public static void main(String args[]) { Employee[] emptyArray1 = returnEmptyEmployeeArray(); Employee[] emptyArray2 = returnAnonymousEmptyArray(); System.out.println("First Array length: "+emptyArray1.length); System.out.println("Second Array length: "+emptyArray2.length); } public static Employee[] returnEmptyEmployeeArray() { // Declaring Array of type Employee and allocating memory Employee[] emptyArray = new Employee[]{}; return emptyArray; } public static Employee[] returnAnonymousEmptyArray() { // Return Anonymous Array block return new Employee[]{}; } } |
Output:
Further reading:
3.4 Using Apache Commons Library – Array Utils Package
The Apache Commons API provides powerful and reusable Java components and dependencies that we can embed into our applications and programs. Here, to return an empty array in we can use the inbuilt functionality of this package.
There are two ways we can return empty array using the Apache Commons lang3 package:
- Return Using
EMPTY_STRING_ARRAY
 field of ArrayUtils Class. - Return Using
toArray()
method of ArrayUtils Class.
We can use the ArrayUtils
class of the Apache Commons Library by importing with the following dependency. For ease we will use the JAR file component of Apache Commons Lang package. To setup the JAR file component for this package we follow these steps:
- Download the Apache Commons Lang JAR.
- Extract the ZIP file and keep the commons-lang3-3.12.0 JAR in separate folder.
- Go to your IDE (Eclipse/Intellij) then right click on package name go to -> Configure Build Path.
- Go to libraries -> Click on Classpath -> Add External JAR’s.
- Select the commons-lang3-3.12.0Â JAR and click Apply and close.
The JAR will then be added to your Java Application after this we can just import the required classes from this package. Now, let us look into the steps.
3.4.1 Return Using EMPTY_STRING_ARRAY
 field of ArrayUtils Class
The ArrayUtils class has a static field EMPTY_STRING_ARRAY which returns a empty String array. It has similar other static fields which return int, char, float etc. type of arrays.
3.4.2 Return Using toArray()
method of ArrayUtils Class
The ArrayUtils class has a method toArray() which can return any type of array based on the the type it is referenced to it can be a object or a primitive type array. It automatically casts the return type based on the method definition.
Let us have a look at the example code to implement the two methods.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 |
import org.apache.commons.lang3.ArrayUtils; // importing Apache Commons lang3 package class Employee { int id; String name; } public class Java2Blog { public static void main(String args[]) { String[] stringArray = returnEmptyStringArray(); int[] intArray = returnEmptyIntArray(); Employee[] emptyArray = returnEmptyEmployeeArray(); System.out.println("String Array length: "+stringArray.length); System.out.println("Integer Array length: "+intArray.length); System.out.println("Employee Array length "+emptyArray.length); } public static String[] returnEmptyStringArray() { // returns empty String array return ArrayUtils.EMPTY_STRING_ARRAY; } public static int[] returnEmptyIntArray() { // returns empty Int array return ArrayUtils.EMPTY_INT_ARRAY; } public static Employee[] returnEmptyEmployeeArray() { // here we return Empty array of type Employee return ArrayUtils.toArray(); } } |
Output:
That’s all about the articles we listed different methods to Return empty array in java with demonstrated examples. You can try them in your Local IDE for a clear understanding. Feel free to reach out to us for any queries/suggestions.