Check If a String is Empty or Null in Java - Utility Methods


In this short article, we will discuss standard utility methods to check if a String is empty or null in Java.

String Empty or Null Utility Methods

  1. isEmptyOrNull(final CharSequence cs) - Checks if a CharSequence is empty ("") or null.
  2. isNotEmptyOrNull(final CharSequence cs) - Checks if a CharSequence is not empty ("") and not null.

1. isEmptyOrNull(final CharSequence cs)

Checks if a CharSequence is empty ("") or null.
 public static boolean isEmptyOrNull(final CharSequence cs) {
        return cs == null || cs.length() == 0;
 }

2. isNotEmptyOrNull(final CharSequence cs)

Checks if a CharSequence is not empty ("") and not null.

    public static boolean isEmptyOrNull(final CharSequence cs) {
        return cs == null || cs.length() == 0;
    }

    public static boolean isNotEmptyOrNull(final CharSequence cs) {
        return !isEmptyOrNull(cs);
    }

Complete Example - Check If a String is Empty or Null in Java

package net.javaguides.lang;

public class StringNullOrEmptyExample {

    public static void main(String[] args) {
        System.out.println(isEmptyOrNull(null));
        System.out.println(isEmptyOrNull(""));
        System.out.println(isEmptyOrNull(" "));
        System.out.println(isEmptyOrNull("bob"));
        System.out.println(isEmptyOrNull("  bob  "));

        System.out.println(isNotEmptyOrNull(null));
        System.out.println(isNotEmptyOrNull(""));
        System.out.println(isNotEmptyOrNull(" "));
        System.out.println(isNotEmptyOrNull("bob"));
        System.out.println(isNotEmptyOrNull("  bob  "));

    }

    public static boolean isEmptyOrNull(final CharSequence cs) {
        return cs == null || cs.length() == 0;
    }

    public static boolean isNotEmptyOrNull(final CharSequence cs) {
        return !isEmptyOrNull(cs);
    }
}
Output:
true
true
false
false
false
false
false
true
true
true

Related Articles

Comments