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) {
    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
    return pos < 0;

2 thoughts on “Checks for whitespaces only string

  1. From my point of view escape analysis should make the first version pretty fast so I don’t see any problem with it. Even if not it can be optimized easily if necessary. Whilst the second one is preamture optimization in a very bad form. Reverse loops are uncommon and thus hard to read. The comment repeats the code and most annoying: It simply not works! It checks for spaces only instead os whitespace only! The fact that it might be slow for big strings (as it doesn’t break on first non space character) is not important. That can be easily optimized if ncessary… 😉

    • Hi Bernd,

      I guess you misunderstood the problem. The goal is to detect whether a given String contains whitespace only (meaning boolean result).

      In the first method, calling trim() would potentially creates a new String instance (see javadoc of trim), which escape analysis can’t help, as it is needed for the equals() call.

      In the second method, it just detect if the string is whitespace only, hence no new object instance is created. Besides, the check for <= ' ' is just the same as what trim does (see trim javadoc). And if you look at how trim() is implemented, there is no way that the second method could be slower. For the comment, it's not repeating the logic, as it states that the check for <= ' ' is to make it logically the same as what trim() does for whitespace check. Regarding the comment about reverse loop, I think in this example is simple enough that anyone learned about while loop can understand it.

Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s