[java] Best way to verify string is empty or null

i am sure this must have been asked before in different ways - as isEmptyOrNull is so common yet people implement it differently. but i have below curious query in terms of best available approach which is good for memory and performance both.

1) Below does not account for all spaces like in case of empty XML tag

return inputString==null || inputString.length()==0;

2) Below one takes care but trim can eat some performance + memory

return inputString==null || inputString.trim().length()==0;

3) Combining one and two can save some performance + memory (As Chris suggested in comments)

return inputString==null || inputString.trim().length()==0 || inputString.trim().length()==0;

4) Converted to pattern matcher (invoked only when string is non zero length)

private static final Pattern p = Pattern.compile("\\s+");

return inputString==null || inputString.length()==0 || p.matcher(inputString).matches();

5) Using libraries like - Apache Commons (StringUtils.isBlank/isEmpty) or Spring (StringUtils.isEmpty) or Guava (Strings.isNullOrEmpty) or any other option?

This question is related to java regex string trim is-empty

The answer is


To detect if a string is null or empty, you can use the following without including any external dependencies on your project and still keeping your code simple/clean:

if(myString==null || myString.isEmpty()){
    //do something
}

or if blank spaces need to be detected as well:

if(myString==null || myString.trim().isEmpty()){
    //do something
}

you could easily wrap these into utility methods to be more concise since these are very common checks to make:

public final class StringUtils{

    private StringUtils() { }   

    public static bool isNullOrEmpty(string s){
        if(s==null || s.isEmpty()){
            return true;
        }
        return false;
    }

    public static bool isNullOrWhiteSpace(string s){
        if(s==null || s.trim().isEmpty()){
            return true;
        }
        return false;
    }
}

and then call these methods via:

if(StringUtils.isNullOrEmpty(myString)){...}

and

if(StringUtils.isNullOrWhiteSpace(myString)){...}


Just to show java 8's stance to remove null values.

String s = Optional.ofNullable(myString).orElse("");
if (s.trim().isEmpty()) {
    ...
}

Makes sense if you can use Optional<String>.


If you have to test more than one string in the same validation, you can do something like this:

import java.util.Optional;
import java.util.function.Predicate;
import java.util.stream.Stream;

public class StringHelper {

  public static Boolean hasBlank(String ... strings) {

    Predicate<String> isBlank = s -> s == null || s.trim().isEmpty();

    return Optional
      .ofNullable(strings)
      .map(Stream::of)
      .map(stream -> stream.anyMatch(isBlank))
      .orElse(false);
  }

}

So, you can use this like StringHelper.hasBlank("Hello", null, "", " ") or StringHelper.hasBlank("Hello") in a generic form.


With the openJDK 11 you can use the internal validation to check if the String is null or just white spaces

import jdk.internal.joptsimple.internal.Strings;
...

String targetString;
if (Strings.isNullOrEmpty(tragetString)) {}

This one from Google Guava could check out "null and empty String" in the same time.

Strings.isNullOrEmpty("Your string.");

Add a dependency with Maven

<dependency>
  <groupId>com.google.guava</groupId>
  <artifactId>guava</artifactId>
  <version>20.0</version>
</dependency>

with Gradle

dependencies {
  compile 'com.google.guava:guava:20.0'
}

Optional.ofNullable(label)
.map(String::trim)
.map(string -> !label.isEmpty)
.orElse(false)

OR

TextUtils.isNotBlank(label);

the last solution will check if not null and trimm the str at the same time


springframework library Check whether the given String is empty.

f(StringUtils.isEmpty(str)) {
    //.... String is blank or null
}

You can make use of Optional and Apache commons Stringutils library

Optional.ofNullable(StringUtils.noEmpty(string1)).orElse(string2);

here it will check if the string1 is not null and not empty else it will return string2


Apache Commons Lang has StringUtils.isEmpty(String str) method which returns true if argument is empty or null


Simply and clearly:

if (str == null || str.trim().length() == 0) {
    // str is empty
}

In most of the cases, StringUtils.isBlank(str) from apache commons library would solve it. But if there is case, where input string being checked has null value within quotes, it fails to check such cases.

Take an example where I have an input object which was converted into string using String.valueOf(obj) API. In case obj reference is null, String.valueOf returns "null" instead of null.

When you attempt to use, StringUtils.isBlank("null"), API fails miserably, you may have to check for such use cases as well to make sure your validation is proper.


Useful method from Apache Commons:

 org.apache.commons.lang.StringUtils.isBlank(String str)

https://commons.apache.org/proper/commons-lang/javadocs/api-2.6/org/apache/commons/lang/StringUtils.html#isBlank(java.lang.String)


Examples related to java

Under what circumstances can I call findViewById with an Options Menu / Action Bar item? How much should a function trust another function How to implement a simple scenario the OO way Two constructors How do I get some variable from another class in Java? this in equals method How to split a string in two and store it in a field How to do perspective fixing? String index out of range: 4 My eclipse won't open, i download the bundle pack it keeps saying error log

Examples related to regex

Why my regexp for hyphenated words doesn't work? grep's at sign caught as whitespace Preg_match backtrack error regex match any single character (one character only) re.sub erroring with "Expected string or bytes-like object" Only numbers. Input number in React Visual Studio Code Search and Replace with Regular Expressions Strip / trim all strings of a dataframe return string with first match Regex How to capture multiple repeated groups?

Examples related to string

How to split a string in two and store it in a field String method cannot be found in a main class method Kotlin - How to correctly concatenate a String Replacing a character from a certain index Remove quotes from String in Python Detect whether a Python string is a number or a letter How does String substring work in Swift How does String.Index work in Swift swift 3.0 Data to String? How to parse JSON string in Typescript

Examples related to trim

How to remove whitespace from a string in typescript? Strip / trim all strings of a dataframe Best way to verify string is empty or null Does swift have a trim method on String? Trim specific character from a string Trim whitespace from a String Remove last specific character in a string c# How to delete specific characters from a string in Ruby? How to Remove the last char of String in C#? How to use a TRIM function in SQL Server

Examples related to is-empty

ValueError when checking if variable is None or numpy.array Best way to verify string is empty or null Check string for nil & empty What is the best way to test for an empty string in Go? Detect if an input has text in it using CSS -- on a page I am visiting and do not control? Checking if a collection is empty in Java: which is the best method? How to check if a file is empty in Bash? Check if array is empty or null How to convert empty spaces into null values, using SQL Server? VBA Check if variable is empty