Efficient and Elegant Null Checks in Java Using Utility Classes
This article explains how to perform efficient and elegant null checks in Java by first identifying the data type, then selecting the appropriate utility class such as StringUtils, ObjectUtils, Collections or CollectionUtils, and finally applying the class’s isEmpty method with code examples for strings, arrays, lists, maps, and more.
NullPointerException is a common bug; many developers add a !=null check to solve it.
Frequent use of !=null can be cumbersome; we can handle it efficiently and elegantly.
Step 1: Identify the data type (String, Object, List, Array, Map, etc.).
Step 2: Choose the corresponding utility class.
String → StringUtils
Object → ObjectUtils
Array → Arrays
List and Map → Collections, CollectionUtils
Step 3: Use the utility class to perform the check.
1. For String, use StringUtils.isEmpty:
String str = "";
StringUtils.isEmpty(str); // trueThe isEmpty method checks both null and empty string.
2. For Object, use ObjectUtils.isEmpty:
Object obj = null;
ObjectUtils.isEmpty(obj); // true3. For Map, also use ObjectUtils.isEmpty:
Map
map = Collections.emptyMap();
ObjectUtils.isEmpty(map); // true4. For List, use ObjectUtils.isEmpty:
List
list = Collections.EMPTY_LIST;
ObjectUtils.isEmpty(list); // true5. For arrays, ObjectUtils.isEmpty works as well:
// array
Object[] objArr = null;
ObjectUtils.isEmpty(objArr); // trueObjectUtils.isEmpty handles Optional, CharSequence, arrays, Collections, and Maps, covering most data types.
However, it only checks collection size, so a List with a single null element is considered non‑empty:
List
list = Collections.singletonList(null);
ObjectUtils.isEmpty(list); // falseFor such cases, iterate over elements, e.g. using Arrays.stream:
Arrays.stream(list.toArray()).allMatch(ObjectUtils::isEmptyisNull);For Map emptiness, CollectionUtils.isEmpty provides a concise check:
Map
map = Collections.emptyMap();
CollectionUtils.isEmpty(map); // trueSimilarly, CollectionUtils.isEmpty(list) checks both null and empty list.
Conclusion
Null checks can be performed in three steps: determine the data type, select the appropriate utility class, and apply its isEmpty method. Use StringUtils for strings, ObjectUtils for most other types, and CollectionUtils for collections when needed.
Selected Java Interview Questions
A professional Java tech channel sharing common knowledge to help developers fill gaps. Follow us!
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.