Checks If a String is Not Empty and Not Null in Java

In this post, we demonstrate how to check if a String is not empty and not null in Java with an example.

Checks If a String is Not Empty and Not Null in Java

package net.javaguides.corejava.string;

public class StringNotNullAndNotEmpty {

    public static void main(String[] args) {
        System.out.println(isNotEmpty(null));
        System.out.println(isNotEmpty(""));
        System.out.println(isNotEmpty("sourcecodeexamples"));
    }
    /**
     * <p>
     * Checks if a CharSequence is empty ("") or null.
     * </p>
     * 
     * @param cs
     *            the CharSequence to check, may be null
     * @return {@code true} if the CharSequence is empty or null
     * @since 3.0 Changed signature from isEmpty(String) to
     *        isEmpty(CharSequence)
     */
    public static boolean isEmpty(final CharSequence cs) {
        return cs == null || cs.length() == 0;
    }

    /**
     * <p>
     * Checks if a CharSequence is not empty ("") and not null.
     * </p>
     * 
     * @param cs
     *            the CharSequence to check, may be null
     * @return {@code true} if the CharSequence is not empty and not null
     * @since 3.0 Changed signature from isNotEmpty(String) to
     *        isNotEmpty(CharSequence)
     */
    public static boolean isNotEmpty(final CharSequence cs) {
        return !isEmpty(cs);
    }
}
Output:
false
false
true

Reference


Comments