Check if string is null or empty

This example will show how to check if a String is null or empty using java, guava and apache commons. A common error when working with Strings is a NullPointerException which is thrown when you try to use a reference of an object that points to no location in memory. In other words, you try to make a call to an object or method that doesn't exist. The technique shown below if used will help prevent these exceptions. If you are working with collections you should consider Effective Java Item 43: Return empty arrays or collections, not nulls.

Straight up Java

This snippet will show how to check if a String is null and its length is greater than zero to prevent a NullPointerException. This approach is effective but verbose and is often replaced by a utility shown below.

Check w/ String.length()

@Test
public void string_is_null_or_empty_java () {

    String outputVal = null;
    String stringToCheck = "abc";

    if (stringToCheck != null && stringToCheck.length() > 0) {
        outputVal = "do some work";
    }

    assertEquals("do some work", outputVal);
}

Check w/ String.isEmpty()

@Test
public void string_is_null_or_empty_isempty () {

    String outputVal = null;
    String stringToCheck = "abc";

    if (stringToCheck != null && !stringToCheck.isEmpty()) {
        outputVal = "do some work";
    }

    assertEquals("do some work", outputVal);

}

Google Guava

This snippet will show how to check if a string is null or empty with guava's Strings.isNullOrEmpty static utility.

@Test
public void string_is_null_or_empty_guava () {

    String outputVal = null;
    String stringToCheck = "abc";

    if (!Strings.isNullOrEmpty(stringToCheck)) {
        outputVal = "do some work";
    };

    assertEquals("do some work", outputVal);
}

Apache Commons

Apache commons StringUtils.isNotEmpty will checks if a String is not empty and not null.

@Test
public void string_is_null_or_empty_apache () {


    String outputVal = null;
    String stringToCheck = "abc";

    if (StringUtils.isNotEmpty(stringToCheck)) {
        outputVal = "do some work";
    };

    assertEquals("do some work", outputVal);
}