a shot of dev knowledge

RELATED TAGS

What is StringUtils.isNotEmpty in Java?

isNotEmpty() is a static method of the StringUtils class that is used to check if the given string is not empty.

If a string does not satisfy any of the criteria below, then the string is considered to be empty.

  1. The length of the string is zero.
  2. The string points to a null reference.

How to import StringUtils

The definition of StringUtils 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 StringUtils class as follows.


import org.apache.commons.lang3.StringUtils;

Syntax


public static boolean isNotEmpty(CharSequence cs)

Parameters

  • CharSequence cs: the character sequence/string to check.

Return value

This method returns true if the string is not null or if the length of the string is greater than zero; otherwise, the function returns false.

Code

import org.apache.commons.lang3.StringUtils;

public class Main {

    public static void main(String[] args) {
        // Example 1
        String s = "543234";
        System.out.printf("The output of StringUtils.isNotEmpty() for the string - '%s' is %s", s, StringUtils.isNotEmpty(s));
        System.out.println();

        // Example 2
        s = "";
        System.out.printf("The output of StringUtils.isNotEmpty() for the string - '%s' is %s", s, StringUtils.isNotEmpty(s));
        System.out.println();

        // Example 3
        s = null;
        System.out.printf("The output of StringUtils.isNotEmpty() for the string - '%s' is %s", s, StringUtils.isNotEmpty(s));
        System.out.println();
    }
}

Output

The output of the code will be as follows.


The output of StringUtils.isNotEmpty() for the string - '543234' is true
The output of StringUtils.isNotEmpty() for the string - '' is false
The output of StringUtils.isNotEmpty() for the string - 'null' is false

Explanation

Example 1

  • string - "543234"

The method returns true, as the string is not null and has a length greater than zero.

Example 2

  • string - ""

The method returns false, as the length of the string is zero.

Example 3

  • string - null

The method returns false, as the string points to a null reference.

RELATED TAGS

RELATED COURSES

View all Courses

Keep Exploring