Best way to verify string is empty or null
Asked Answered
H

15

41

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?

Heated answered 14/9, 2015 at 14:20 Comment(7)
inputString!=null && inputString.isEmpty(); more refined inputString!=null && inputString.trim().isEmpty();Nuss
You can also use Apache String utils isEmpty() this does the null check as well as space checks.Nuss
isEmpty is "new" in java 6 and implementations that are older or want to stay java 5 compatible will have to use length check.Caban
If you do return inputString==null || inputString.length()==0 || inputString.trim().length()==0; (combining 1 and 2) then trim is only invoked on non-zero-length string. You might add 3 to it too.,Evenson
@ChristianFries Yes, I agree - same approach can be used for both trim() and pattern matcher. But let me ask it this way - trim() or matcher() which one is costlier?Heated
Guava has Strings.isNullOrEmpty() which i am using the most at the moment!Heated
Possible duplicate of Check whether a string is not null and not emptyConform
P
4

Haven't seen any fully-native solutions, so here's one:

return str == null || str.chars().allMatch(Character::isWhitespace);

Basically, use the native Character.isWhitespace() function. From there, you can achieve different levels of optimization, depending on how much it matters (I can assure you that in 99.99999% of use cases, no further optimization is necessary):

return str == null || str.length() == 0 || str.chars().allMatch(Character::isWhitespace);

Or, to be really optimal (but hecka ugly):

int len;
if (str == null || (len = str.length()) == 0) return true;
for (int i = 0; i < len; i++) {
  if (!Character.isWhitespace(str.charAt(i))) return false;
}
return true;

One thing I like to do:

Optional<String> notBlank(String s) {
  return s == null || s.chars().allMatch(Character::isWhitepace))
    ? Optional.empty()
    : Optional.of(s);
}

...

notBlank(myStr).orElse("some default")
Profitsharing answered 18/5, 2019 at 20:16 Comment(0)
N
44

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)

Nadler answered 14/9, 2015 at 15:21 Comment(2)
Guava has Strings.isNullOrEmpty() which I am using quite often these daysHeated
isNullOrEmpty does not check the case when the input string consists of multiple whitespacesGuadalupe
C
25

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)){...}

Cafeteria answered 14/9, 2015 at 14:27 Comment(6)
updated thanks. I inevitably make that mistake every time and then compile it, see the error, and realize ive made this mistake for the 9 billionth time :)Cafeteria
@Caban or statement in java is short-circuit. It will break if myString is nullGernhard
@JamesWierzba answer was if (s.isEmpty||s==null) which does short circuit with a NPE in case of null :) removed comment to avoid confusion.Caban
And it doesnt take care of blank spaces :)Heated
The question only mentioned null or empty. If blank spaces need to be detected as well, then this can easily be changed to if(myString==null || myString.trim().isEmpty()){...}Cafeteria
String now has a .isBlank() methodCallean
B
15

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>.

Bermudez answered 14/9, 2015 at 14:46 Comment(6)
Thanks Joop, I think this one is also a clean solution - It will not work for multi-space blank strings like " ".Heated
@prash: added a trim for good order, but apache commons is unbeatable. ;)Bermudez
I have to say I think that the use of Optional is infecting the Java community like a bad disease. I have never before seen a feature that takes so much extra typing to achieve was is so simple yet adopted by so many sheeple at a time when competitive languages are going for more terse solutions. It must make non Java developers laugh at us. I haven't even mentioned the extra CPU and memory consumption when OptionalS are instantiated returned by methods that get called millions of times a second - but it's all running in the cloud so CPU and memory are almost free right?Achromatize
@Achromatize I agree that 1. some other languages have better (designed) constructs, 2. Optional is a late addition, an artifact with an unripe API. But it is 1. better than null, 2. allows some nice operations à la map.Bermudez
@JoopEggen I've been using polymorphic "Null" classes/objects since C++ days to store items in template/generic collections that "represent" null but I've recently been working in large scale systems that already have performance issues (CPU + Memory) processing thousands of txns/second. If we change working code that returns null by wrapping each return value in an Optional we'll be allocating thousands more objects on the heap every second, making a struggling system do more work for no benefit (IMHO) and a lot of pain or increased infrastructure costs to cope. Conceptually awesome though!Achromatize
@Achromatize 100% true; also waves of small refactorings is productive (though one should refactor during development to keeep the code fine). Performance might surprise, but is indeed not optimal.Bermudez
A
8

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'
}
Athamas answered 11/11, 2016 at 9:23 Comment(3)
Could you mention which library you are using the Strings class from?Megaron
From "Google Guava". I have edited the answer with library.Athamas
Guava dependency size: 2.3 MB for only checking if a string is null or empty... Guava have a lack of modularization.Taurus
P
4

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

Prunella answered 14/9, 2015 at 15:14 Comment(0)
U
4

Using the Spring Framework library check whether the given String is empty:

f(ObjectUtils.isEmpty(str)) {
    //... The string is blank or null
}
Upcoming answered 19/3, 2019 at 10:41 Comment(1)
As of Spring 5.3 isEmpty is deprecated. Instead, it's recommended to use following alternatives: hasLength(String), hasText(String) or ObjectUtils.isEmpty(Object)Staford
P
4

Haven't seen any fully-native solutions, so here's one:

return str == null || str.chars().allMatch(Character::isWhitespace);

Basically, use the native Character.isWhitespace() function. From there, you can achieve different levels of optimization, depending on how much it matters (I can assure you that in 99.99999% of use cases, no further optimization is necessary):

return str == null || str.length() == 0 || str.chars().allMatch(Character::isWhitespace);

Or, to be really optimal (but hecka ugly):

int len;
if (str == null || (len = str.length()) == 0) return true;
for (int i = 0; i < len; i++) {
  if (!Character.isWhitespace(str.charAt(i))) return false;
}
return true;

One thing I like to do:

Optional<String> notBlank(String s) {
  return s == null || s.chars().allMatch(Character::isWhitepace))
    ? Optional.empty()
    : Optional.of(s);
}

...

notBlank(myStr).orElse("some default")
Profitsharing answered 18/5, 2019 at 20:16 Comment(0)
H
2
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

Hathcock answered 2/8, 2017 at 10:2 Comment(1)
TextUtils from apache httpcore.Bedwell
Y
1

Simply and clearly:

if (str == null || str.trim().length() == 0) {
    // str is empty
}
Yulandayule answered 25/10, 2017 at 7:11 Comment(0)
A
1

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.

Antrorse answered 15/2, 2018 at 14:2 Comment(0)
S
1

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)) {}
Soileau answered 18/3, 2020 at 3:53 Comment(1)
Nice, they stole this from C# I think. Missed it for a while.Moisten
J
1

latest spring using hasText to validate a String as shown below

import org.springframework.util.StringUtil;
    
    class Test {
       public boolean isNullOrEmpty(String data) {
          return !StringUtils.hasText(data);
       }
    }
Johannajohannah answered 6/2, 2024 at 1:59 Comment(0)
M
0

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

Marsh answered 26/3, 2019 at 6:38 Comment(0)
O
0

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.

Opsis answered 23/5, 2019 at 1:5 Comment(2)
technically it is a good answer but performance wise may not be bestHeated
It looks like competition ))) Who can implement it longer!Lob
F
0

We can make use of below

Optional.ofNullable(result).filter(res -> StringUtils.isNotEmpty(res))
            .ifPresent( s-> val.set(s));
Forepart answered 14/5, 2021 at 6:18 Comment(0)

© 2022 - 2025 — McMap. All rights reserved.