Java String isBlank() Utility Method - Check if String is a Blank

This page contains the source code of the Java String isBlank() utility method - This method checks if a CharSequence is empty (""), null, or whitespace only. 

This method is similar to isEmpty()but additionally checks for whitespace.

Java String isBlank() Utility Method

The following String isBlank() utility method checks if a CharSequence is empty (""), null or whitespace only.:
public static boolean isBlank(final CharSequence cs) {
    int strLen;
    if (cs == null || (strLen = cs.length()) == 0) {
         return true;
    }
    for (int i = 0; i < strLen; i++) {
         if (!Character.isWhitespace(cs.charAt(i))) {
             return false;
         }
    }
    return true;
}
JUnit test case for isBlank(final CharSequence cs) method:
@Test
public void isBlankTest() {
    assertTrue(isBlank(null));
    assertTrue(isBlank(""));
    assertTrue(isBlank(" "));
    assertFalse(isBlank("bob"));
    assertFalse(isBlank("  bob  "));
}

Related Utility Methods


Comments