Check If a String is Empty or Null in Java

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

We can directly use these utility methods to null or empty check for Strings in Java.
Learn all about Java String at Java String Handling Tutorial.

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)

Here is a utility method to check if a CharSequence or String is empty ("") or null:
 public static boolean isEmptyOrNull(final CharSequence cs) {
        return cs == null || cs.length() == 0;
 }

2. isNotEmptyOrNull(final CharSequence cs)

Here is a utility method to check if a CharSequence or String 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