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;
}

Stupid programming II

I came across a segment of Java code like this during a code review:

String str = "" + 10;

Sometimes I really don’t know what’s in people head. Isn’t it a lot more simpler/clearer/better/faster to do it as:

String str = "10";

If it is up to me, we should banish people writing code like this to write single line of code again.