Checks for whitespaces only string

Someone tries to have a method in Java that checks if a string contains only whitespace characters, and ended up with an implementation like this:

boolean isWhitespaceOnly(String str) {
    // DON'T DO THIS, EXPLAINED BELOW
    return str.trim().equals("");
}

So, what’s wrong with it?

  1. The trim() method will create a new String instance (only exception is an empty string or the first and last characters are not whitespaces. Check Java API doc.).
  2. Always use isEmpty() rather than .equals("") to check if a string is empty, as it is always faster.

In fact we should just inspect characters in the string and return true when we only see whitespaces. It would be faster (as we can terminate whenever we see a non-whitespace) and no new instance being created.

boolean isWhitespaceOnly(String str) {
    int pos = str.length() - 1;
    while (pos >= 0 && str.charAt(pos) <= ' ') {   // checking of <= ' ' is the same contract as the trim() does
        pos--;
    }        
    return pos < 0;
}
Advertisements