Master Null Checks in Java: When to Use StringUtils, ObjectUtils, and CollectionUtils
This article explains how to replace repetitive null‑checks in Java with the appropriate utility classes—StringUtils for strings, ObjectUtils for objects, arrays, lists and maps, and CollectionUtils for collections—providing step‑by‑step guidance, code examples, and a discussion of each method's limitations.
NullPointerException is a frequent bug; instead of sprinkling manual != null checks, you can use the appropriate utility classes provided by Spring or Apache Commons.
Step 1 – Identify the data type
The value may be a String , a custom Object , an Array , a List or a Map .
Step 2 – Choose the right utility class
String → StringUtils Object, Array, List, Map → ObjectUtils List/Map also →
CollectionUtilsStep 3 – Perform the check
Examples:
String str = "";
StringUtils.isEmpty(str); // true Object obj = null;
ObjectUtils.isEmpty(obj); // true Map<String,Object> map = Collections.emptyMap();
ObjectUtils.isEmpty(map); // true List<Integer> list = Collections.EMPTY_LIST;
ObjectUtils.isEmpty(list); // true Object[] objArr = null;
ObjectUtils.isEmpty(objArr); // trueThe source of ObjectUtils.isEmpty(Object) checks for null, Optional, CharSequence, arrays, collections and maps, returning true when the value is considered empty.
public static boolean isEmpty(@Nullable Object obj) {
if (obj == null) {
return true;
}
if (obj instanceof Optional) {
return !((Optional) obj).isPresent();
}
if (obj instanceof CharSequence) {
return ((CharSequence) obj).length() == 0;
}
if (obj.getClass().isArray()) {
return Array.getLength(obj) == 0;
}
if (obj instanceof Collection) {
return ((Collection) obj).isEmpty();
}
if (obj instanceof Map) {
return ((Map) obj).isEmpty();
} else {
return false;
}
}This method cannot detect a collection that contains a single null element; it only checks size. For such cases you need to inspect each element, e.g.:
Arrays.stream(list.toArray()).allMatch(ObjectUtils::isEmptyisNull);For maps you can use CollectionUtils.isEmpty(map) which internally checks map == null || map.isEmpty().
public static boolean isEmpty(@Nullable Map<?, ?> map) {
return map == null || map.isEmpty();
}In summary, determine the data type, pick the corresponding utility class, and invoke its isEmpty (or isEmptyisNull) method to replace repetitive != null checks.
Top Architect
Top Architect focuses on sharing practical architecture knowledge, covering enterprise, system, website, large‑scale distributed, and high‑availability architectures, plus architecture adjustments using internet technologies. We welcome idea‑driven, sharing‑oriented architects to exchange and learn together.
How this landed with the community
Was this worth your time?
0 Comments
Thoughtful readers leave field notes, pushback, and hard-won operational detail here.
