I am needing to write my own IsNullOrWhiteSpace check for Java but am wondering if this is the best method to do so

public static boolean isStringNullOrWhiteSpace(String value) {
    if (isStringNullOrEmpty(value)){
        return true;
    }

    for (Character chars : value.toCharArray()){
        if (!Character.isWhitespace(chars)) return false;
    }

    return true;
}
  • I'm curious, what is the class called, and what other methods are in it? – 200_success Nov 14 '14 at 11:24
  • @200_success it is called StringUtils. Basically, it is trying to simulate .NET string utilities. – David Pilkington Nov 14 '14 at 11:25
  • 1
    An emptystring is neither whitespace nor null.. your method still returns true for it. Either that shouldn't be the case or your method isn't named correctly – Vogel612 Nov 14 '14 at 11:32
  • 3
    @Vogel612 This is how .NET behaves. Like I said, I am trying to simulate .NET behaviour. – David Pilkington Nov 14 '14 at 11:35
  • 3
    The .NET source code for the String.IsNullOrWhiteSpace method is available online. – Alexander Nov 14 '14 at 17:10
up vote 9 down vote accepted

You'd have to check a profiler, but otherwise just iterating over the string would be best, since you then don't have any allocations going on, i.e.:

public static boolean isStringNullOrWhiteSpace(String value) {
    if (value == null) {
        return true;
    }

    for (int i = 0; i < value.length(); i++) {
        if (!Character.isWhitespace(value.charAt(i))) {
            return false;
        }
    }

    return true;
}
  • 1
    +1. Besides not allocating, this is the most direct translation of the .NET implementation that Alexander linked to. – mjolka Nov 15 '14 at 2:24

I agree that the String should be left out of the name, as this is quite obvious in StringUtils. How about this short version?

public static boolean isNullOrWhiteSpace(String value) {
    return value == null || value.trim().isEmpty();
}
  • Just a note that this is basically how it is done in .NET although they check the length of the trimmed string rather than using isEmtpy() like this return value == null || value.trim().length == 0; although they claim that it has better performance than just writing that code would. – Spaceman Spiff Nov 14 '14 at 14:54
  • Note: this is equivalent to the String.IsNullOrEmpty method in .NET, whereas String.IsNullOrWhiteSpace is the appropriate method to use when also checking for strings with only white space characters. The OP's proposed solution is practically identical to the .NET method (aside from the additional method call in the stack). – Alexander Nov 14 '14 at 17:08
  • 1
    I'm not sure I get your note's point, @Alexander. C#'s String.IsNullOrEmpty returns true if the given string is null or empty string, but false for "\t \r\n". C#'s String.IsNullOrWhiteSpace, and the answer above, will return true for null, empty string, and "\t \r\n". This answer is equivalent to (and more readable than) C#'s String.IsNullOrWhiteSpace, which is what the OP is trying to replicate. – JMD Nov 14 '14 at 17:56
  • 4
    This method will produce different results in some nontrivial cases. isWhitespace and trim have different notion on what is a whitespace character. For example NULL ("\0") is trimmed but isWhitespace returns false. IDEOGRAPHIC SPACE ("\u3000") is another example. – Banthar Nov 15 '14 at 9:44

Having "String" in the method name is doubly redundant: first, because it is in a class called StringUtils, and also because the compiler will handle any overloading based on the parameter type. .NET does likewise and calls it IsNullOrWhitespace.

You could generalize it for the CharSequence interface.

public static boolean isNullOrWhitespace(CharSequence value) {
    if (value == null) {
        return true;
    }

    for (int i=0; i < value.length(); i++) {
        if (!Character.isWhitespace(value.charAt(i))) {
            return false;
        }
    }

    return true;
}

Or if you're using Java 8:

public static boolean isNullOrWhitespace(CharSequence value) {
    return value == null || value.codePoints().allMatch(c -> Character.isWhitespace(c));
}
  • Cheers for the nice Java 8 solution. Doesn't actually fit the requirements of emulating the .NET behaviour, but, as an implementation that one would expect from the method's name, it is very good. – Nihathrael Nov 14 '14 at 13:04
  • @Nihathrael hm, how does it behave differently? – dusky Nov 14 '14 at 13:25
  • 1
    I think for an empty string yours will return false, I might be missing something? – Nihathrael Nov 14 '14 at 13:42
  • 1
    @Nihathrael From IntStream: true if either all elements of the stream match the provided predicate or the stream is empty, otherwise false. Exactly like C#'s Enumerable.All. – dusky Nov 14 '14 at 14:35

You should be consistent with your coding style. If you use braces {} for single if statements you should use them each time.

You should replace the check isStringNullOrEmpty(value) with (value==null)

public static boolean isStringNullOrWhiteSpace(String value) {
    if (value == null){
        return true;
    }

    for (Character chars : value.toCharArray()){
        if (!Character.isWhitespace(chars)){
             return false;
        }
    }

    return true;
}  

as value.toCharArray() just returns an empty array if value.length() == 0.

For the naming I go with @200_success. You should call it isNullOrWhiteSpace.

Yes, your way of doing the check is fine!

It should be favored over the code snipped in the accepted answer of Nihathrael. That solution is significantly less performant and would be marked as shortcoming by code quality inspection tools. The invocation of trim() may implicate the creation of a new string object.

See also

Have you considered using regular expressions? "Best" is always relative in the context of code, but if I were doing it, I might do something like this:

public static boolean isStringNullOrWhiteSpace(String value) {
    final Pattern pattern = Pattern.compile("^\\w*$");    //pattern for 0 or more whitespace characters
    if (value == null || pattern.matcher(value).find()) {
        return true;
    }
    return false;
}

This basically uses a regular expression for zero or more whitespace characters in a string, and checks your value against it; then returns the result. It's built into java.util.regex. Check it out.

The "empty" part can be also checked by using regex — if the entire string is matched by \s*, then it's empty or whitespace.

Your Answer

 
discard

By clicking "Post Your Answer", you acknowledge that you have read our updated terms of service, privacy policy and cookie policy, and that your continued use of the website is subject to these policies.

Not the answer you're looking for? Browse other questions tagged or ask your own question.