What is Validate.notEmpty() in Java?

notEmpty() is a staticthe methods in Java that can be called without creating an object of the class. method of the Validate class that is used to check whether the given argument array/map/collection/character sequence is not null or empty.

If the array/map/collection/character sequence is either null or empty, the method throws an exception.

How to import Validate

The definition of Validate can be found in the Apache Commons Lang package, which we can add to the Maven project by adding 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.

You can import the Validate class as follows.

import org.apache.commons.lang3.Validate;

Syntax

public static <T> T[] notEmpty(final T[] array, final String message, final Object... values)

Parameters

  • final T[] array: The array to check.

  • final String message: The exception message.

  • final Object... values: The optional values for the formatted exception message.

Return value

This method returns the validated array.

Overloaded methods

  • public static <T> T[] notEmpty(final T[] array)

  • public static <T extends Collection<?>> T notEmpty(final T collection, final String message, final Object... values)

  • public static <T extends Collection<?>> T notEmpty(final T collection)

  • public static <T extends Map<?, ?>> T notEmpty(final T map, final String message, final Object... values)

  • public static <T extends Map<?, ?>> T notEmpty(final T map)

Code

import org.apache.commons.lang3.Validate;
import java.util.Arrays;
public class Main{
public static void main(String[] args){
// Example 1
Integer[] ints = new Integer[]{1, 2, 3};
System.out.printf("Validate.notEmpty(%s) = %s", Arrays.toString(ints), Arrays.toString(Validate.notEmpty(ints)));
System.out.println();
// Example 2
ints = new Integer[0];
String exceptionMessage = "The array must not be null or empty";
System.out.printf("Validate.notEmpty(%s) = %s", Arrays.toString(ints), Arrays.toString(Validate.notEmpty(ints, exceptionMessage)));
System.out.println();
}
}

Output

The output of the code will be as follows:

Validate.notEmpty([1, 2, 3]) = [1, 2, 3]
Exception in thread "main" java.lang.IllegalArgumentException: The array must not be null or empty
	at org.apache.commons.lang3.Validate.notEmpty(Validate.java:249)
	at Main.main(Main.java:16)

Example 1

  • array - [1, 2, 3]

The method returns the input array [1, 2, 3], as the array is not null and not empty.

Example 2

  • array - []

The method throws an IllegalArgumentException exception with the exception message The array must not be null or empty, as the input array is empty.

Free Resources