Java - Write code to Checks if a String is whitespace, empty ("") or null.

Requirements

Write code toChecks if a String is whitespace, empty ("") or null.

Demo

//package com.book2s;

public class Main {
    public static void main(String[] argv) {
        String str = "book2s.com";
        System.out.println(isBlank(str));
    }/*  ww  w. j  a  v  a  2 s.  c  o  m*/

    /**
     * <p>
     * Checks if a String is whitespace, empty ("") or null.
     * </p>
     * 
     * <pre>
     * StringUtils.isBlank(null)      = true
     * StringUtils.isBlank("")        = true
     * StringUtils.isBlank(" ")       = true
     * StringUtils.isBlank("bob")     = false
     * StringUtils.isBlank("  bob  ") = false
     * </pre>
     * 
     * @param str
     *            the String to check, may be null
     * @return <code>true</code> if the String is null, empty or whitespace
     * @since 2.0
     */
    public static boolean isBlank(String str) {
        int strLen;
        if (str == null || (strLen = str.length()) == 0) {
            return true;
        }
        for (int i = 0; i < strLen; i++) {
            if (!Character.isWhitespace(str.charAt(i))) {
                return false;
            }
        }
        return true;
    }
}

Related Example