What is ArrayUtils.nullToEmpty in Java?
nullToEmpty is a static method of the ArrayUtils class that returns an null.
The method returns the same array reference if the passed array reference doesn’t point to null.
Add apache commons-lang package
ArrayUtils is defined in the Apache Commons Lang package. To add Apache Commons Lang to the Maven Project, add the following dependency to the pom.xml file.
<dependency>
<groupId>org.apache.commons</groupId>
<artifactId>commons-lang3</artifactId>
<version>3.12.0</version>
</dependency>
For other versions of the commons-lang package, refer to the Maven Repository.
How to import ArrayUtils
You can import the ArrayUtils class as follows.
import org.apache.commons.lang3.ArrayUtils;
Syntax
public static int[] nullToEmpty(final int[] array)
Parameters
final int[] array: the array reference to check fornull.
Return value
This method returns an empty array if the input array is null. Otherwise, it returns the passed array if the input array is not null.
Code
Example 1
array = null
Application of the nullToEmpty function will result in the following empty array: [].
Example 2
array = [1,2]
Application of the nullToEmpty function will result in the same array reference: [1,2].
import org.apache.commons.lang3.ArrayUtils;public class Main {public static void main(String[] args) {int[] array = null;int[] result = ArrayUtils.nullToEmpty(array);System.out.println("Length of the result array is " + result.length);array = new int[]{1};result = ArrayUtils.nullToEmpty(array);System.out.println("Length of the result array is " + result.length);}}
Output
Length of the result array is 0
Length of the result array is 1