In Java, stop writing!= null everywhere! This Is a Better Approach


A common annoyance in Java development is null pointer exceptions. The solution of choice for a lot of developers? Include a brief!= null check. At least on the surface, the issue has been resolved.

However, when these tests begin to accumulate throughout your codebase, they complicate maintenance, clog logic, and make it difficult to read. So, is there a more scalable and clean method?

Of course. Let's have a look at it.

Step 1: Determine the Type of Data
Think about the kind of value you're working with before aiming for!= null. Usually, one of the following applies:
  • String
  • Object or a custom class
  • List
  • Array
  • Map

2. Use the Appropriate Utility Class
Several utility classes designed for these kinds are available in Java and Spring:
  1. StringUtils is the suggested utility class for String types.
  2. Use ObjectUtils for general Object types.
  3. The proper utility class for arrays is Arrays.
  4. You can use Collections or CollectionUtils for collections such as List and Map.
These built-in tools greatly simplify null and empty checks.

1. String
To check for null or empty strings, use StringUtils.isEmpty():  
String name = "";
boolean isBlank = StringUtils.isEmpty(name); // true if null or ""
Internally, it looks for empty and null strings:
public static boolean isEmpty(@Nullable Object str) {
   return str == null || "".equals(str);
}

2. Object
For generic object null and emptiness checks, use ObjectUtils.isEmpty():
Object user = null;
boolean isEmpty = ObjectUtils.isEmpty(user); // true if null

3. Maps
Maps are also handled by ObjectUtils:
Map<String, Object> configMap = new HashMap<>();
boolean isEmptyMap = ObjectUtils.isEmpty(configMap); // true if null or empty

4. Lists
The same is true for lists:
List<String> items = Collections.emptyList();
boolean isListEmpty = ObjectUtils.isEmpty(items); // true

5. Arrays
And arrays:
Integer[] numbers = null;
boolean isArrayEmpty = ObjectUtils.isEmpty(numbers); // true

As you can see, ObjectUtils.isEmpty() is very flexible. What causes it to function with so many different types?
Let's examine how it is implemented:
public static boolean isEmpty(@Nullable Object obj) {
    // Check if obj is null; if so, return true immediately
    if (obj == null) {
      return true;
    }
    // Check if obj is an instance of Optional
    if (obj instanceof Optional) {
      // If yes, use isPresent() to determine if it's empty
      return !((Optional) obj).isPresent();
    }
    // Check if obj is a subtype of CharSequence (e.g., String)
    if (obj instanceof CharSequence) {
      // If yes, treat it as empty if its length is zero
      return ((CharSequence) obj).length() == 0;
    }
    // Check if obj is an array
    if (obj.getClass().isArray()) {
      // Consider it empty if its length is zero
      return Array.getLength(obj) == 0;
    }
    // Check if obj is a subtype of Collection
    if (obj instanceof Collection) {
      // Use the isEmpty() method of Collection to determine if it's empty
      return ((Collection) obj).isEmpty();
    }
    // Check if obj is a subtype of Map
    if (obj instanceof Map) {
      // If yes, cast to Map and use its isEmpty() method to check
      return ((Map) obj).isEmpty();
    }
    // If none of the above, return false
    return false;
}

A wide range of types are covered by this method, including maps, arrays, collections, optional, and string.

However, there are some edge cases, therefore it's not flawless.

Be Wary of False Negative Results
Even if a collection or array may technically be empty if it only has null elements, it will still be regarded as not empty.
List<Integer> list = Collections.singletonList(null);
ObjectUtils.isEmpty(list); // false

Object[] array = new Object[]{null};
ObjectUtils.isEmpty(array); // false
You'll need a more focused approach in these situations.

6. Examine a list for null elements.
To determine if every element is null, use streams:
Arrays.stream(list.toArray()).allMatch(ObjectUtils::isEmptyisNull);

7. For Maps
Use CollectionUtils in Spring for null-safe map checks:
Map<String, Object> map = Collections.emptyMap();
CollectionUtils.isEmpty(map); // true
The basic implementation is as follows:
public static boolean isEmpty(@Nullable Map<?, ?> map) {
    return map == null || map.isEmpty();
}

Two checks are included in this method: if the map is empty and whether it is null. We can avoid additional work by making a direct call.

Bonus: How About List CollectionUtils?
Yes, it does work:
List<Integer> list = null;
CollectionUtils.isEmpty(list); // true

Additionally, the source code:
public static boolean isEmpty(@Nullable Collection<?> collection) {
    return collection == null || collection.isEmpty();
}

By combining the two conditions, this method checks for both null and empty. We may make our code simpler by calling it directly.

Summary: A straightforward three-step procedure can be used to determine if a value is null:

Find out what kind of data it is.
Select the utility class that corresponds to the type.
To carry out the inspection, apply the appropriate technique.
Use the StringUtils tool for String types.

In general, ObjectUtils performs admirably for everything else.

In addition to ObjectUtils, CollectionUtils is a fantastic choice for working with List and Map collections.

You must iterate through the contents of an array or list if you need to verify that every entry is null.
Hi There, I'm Yahya, and I enjoy sharing knowledge and experiences.