Java - Write code to Check that the given CharSequence is neither null nor of length 0.

Requirements

Write code to Check that the given CharSequence is neither null nor of length 0.

Demo

//package com.book2s;

public class Main {
    public static void main(String[] argv) {
        String str = "book2s.com";
        System.out.println(hasLength(str));
    }/* w w w .  jav a2s.c  o  m*/

    /**
     * Check that the given CharSequence is neither {@code null} nor of length
     * 0. Note: Will return {@code true} for a CharSequence that purely consists
     * of whitespace.
     * <p>
     * 
     * <pre>
     * StringUtils.hasLength(null) = false
     * StringUtils.hasLength("") = false
     * StringUtils.hasLength(" ") = true
     * StringUtils.hasLength("Hello") = true
     * </pre>
     * 
     * @param str
     *            the CharSequence to check (may be {@code null})
     * @return {@code true} if the CharSequence is not null and has length
     */
    public static boolean hasLength(CharSequence str) {
        return (str != null && str.length() > 0);
    }

    /**
     * Check that the given String is neither {@code null} nor of length 0.
     * Note: Will return {@code true} for a String that purely consists of
     * whitespace.
     * 
     * @param str
     *            the String to check (may be {@code null})
     * @return {@code true} if the String is not null and has length
     * @see #hasLength(CharSequence)
     */
    public static boolean hasLength(String str) {
        return hasLength((CharSequence) str);
    }
}

Related Exercise