14
\$\begingroup\$

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;
}
\$\endgroup\$
5
  • \$\begingroup\$ I'm curious, what is the class called, and what other methods are in it? \$\endgroup\$ Commented Nov 14, 2014 at 11:24
  • \$\begingroup\$ @200_success it is called StringUtils. Basically, it is trying to simulate .NET string utilities. \$\endgroup\$ Commented Nov 14, 2014 at 11:25
  • 1
    \$\begingroup\$ 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 \$\endgroup\$
    – Vogel612
    Commented Nov 14, 2014 at 11:32
  • 3
    \$\begingroup\$ @Vogel612 This is how .NET behaves. Like I said, I am trying to simulate .NET behaviour. \$\endgroup\$ Commented Nov 14, 2014 at 11:35
  • 3
    \$\begingroup\$ The .NET source code for the String.IsNullOrWhiteSpace method is available online. \$\endgroup\$
    – Alexander
    Commented Nov 14, 2014 at 17:10

8 Answers 8

10
\$\begingroup\$

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;
}
\$\endgroup\$
1
  • 1
    \$\begingroup\$ +1. Besides not allocating, this is the most direct translation of the .NET implementation that Alexander linked to. \$\endgroup\$
    – mjolka
    Commented Nov 15, 2014 at 2:24
17
\$\begingroup\$

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();
}
\$\endgroup\$
4
  • \$\begingroup\$ 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. \$\endgroup\$ Commented Nov 14, 2014 at 14:54
  • \$\begingroup\$ 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). \$\endgroup\$
    – Alexander
    Commented Nov 14, 2014 at 17:08
  • 1
    \$\begingroup\$ 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. \$\endgroup\$
    – JMD
    Commented Nov 14, 2014 at 17:56
  • 4
    \$\begingroup\$ 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. \$\endgroup\$
    – Banthar
    Commented Nov 15, 2014 at 9:44
6
\$\begingroup\$

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.

\$\endgroup\$
4
\$\begingroup\$

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));
}
\$\endgroup\$
4
  • \$\begingroup\$ 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. \$\endgroup\$
    – Nihathrael
    Commented Nov 14, 2014 at 13:04
  • \$\begingroup\$ @Nihathrael hm, how does it behave differently? \$\endgroup\$
    – dusky
    Commented Nov 14, 2014 at 13:25
  • 1
    \$\begingroup\$ I think for an empty string yours will return false, I might be missing something? \$\endgroup\$
    – Nihathrael
    Commented Nov 14, 2014 at 13:42
  • 1
    \$\begingroup\$ @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. \$\endgroup\$
    – dusky
    Commented Nov 14, 2014 at 14:35
3
\$\begingroup\$

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.

\$\endgroup\$
2
\$\begingroup\$

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

\$\endgroup\$
1
\$\begingroup\$

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.

\$\endgroup\$
0
\$\begingroup\$

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

\$\endgroup\$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

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