Null Checks and Optional Usage in Java
This article explains common null‑checking techniques for objects, Lists, and Strings in Java, introduces the Optional class with its creation methods and typical usage scenarios, and compares various utility libraries to help avoid NullPointerException in real‑world projects.
In real projects, missing null checks often lead to NullPointerException . This article first introduces basic null‑checking methods using java.util.Objects.nonNull(obj) , Hutool's ObjectUtil , or simple obj != null .
2. List null checks – Distinguish between a List being non‑null and its size being greater than zero. Common patterns include list != null && list.size() > 0 , list.isEmpty() , or using Hutool's CollUtil.isEmpty . The article shows the source of list.isEmpty() and warns that calling it on a null list still throws NullPointerException .
3. String null checks – When a String is null, calling equals(...) or length() throws NullPointerException . Several approaches are presented:
if(a == null || a.equals("")); if(a == null || a.length() == 0); if(a == null || a.isEmpty());Additionally, Apache Commons StringUtils provides isNotBlank and isNotEmpty methods with example return values.
4. Optional – The Optional class is introduced to prevent NullPointerException . Creation methods ( .empty() , .of(T) , .ofNullable(T) ) and common operations ( isPresent() , ifPresent() , orElse() , orElseGet() , orElseThrow() , map() , flatMap() , get() ) are listed. Sample code shows the internal structure of Optional and typical usage in service layers, demonstrating how a single line with Optional can replace multiple null‑check statements.
5. Summary – Each null‑checking technique has its appropriate scenario; while chain‑style code with Optional can be elegant, it may reduce readability, so developers should choose based on project needs.
Architect's Guide
Dedicated to sharing programmer-architect skills—Java backend, system, microservice, and distributed architectures—to help you become a senior architect.
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.