Debugging and Preventing NullPointerException in Java Backend Data Processing
This article presents a real-world Java backend case where null pointer exceptions arise during data matching and batch insertion, analyzes the root causes in each code line, and offers defensive programming, ternary, Optional, collection checks, and utility methods to safely handle null values.
Hello everyone, this article shares a real case to deepen understanding of NullPointerException (NPE) in Java backend development.
A newly hired intermediate Java developer was assigned a simple task: match third‑party data to internal channel identifiers and batch‑insert the results. After deployment, an NPE occurred during the matching logic.
Accident Reproduction
1. Pseudo Code
Note: The pseudo code is not the actual production code but illustrates the issue; real business logic is often more complex, making NPEs hard to detect in tests.
String channelNo = channelDao.getOne().getChannelNo(); List
thirdDataList = httpClientUtils.getThirdDatas(DateUtils.today()); thirdDataList.stream().filter(o -> channelNo.equals(o.getChannelNo())).collect(Collectors.toList()); thirdDataDao.saveAll(thirdDataList);2. Analysis and Solutions
Four lines of code contain three potential NPEs.
First Line
If channelDao.getOne() returns null , calling getChannelNo() triggers an NPE.
Solution:
// Defensive check
Channel channel = channelDao.getOne();
if (channel == null) {
return;
} // Ternary operator returning empty string
String channelNo = channelDao.getOne() == null ? "" : channelDao.getOne().getChannelNo(); // Using Optional
String channelNo = Optional.ofNullable(channelDao.getOne()).orElse("");Third Line (1)
If thirdDataList is null , calling stream() causes an NPE.
Solution:
// Recommended defensive check using CollectionUtils
if (CollectionUtils.isEmpty(thirdDataList)) {
return;
} // Conditional wrapper (less recommended)
if (CollectionUtils.isNotEmpty(thirdDataList)) {
// proceed with logic
}Third Line (2)
If channelNo is null , the expression channelNo.equals(o.getChannelNo()) throws an NPE.
Solutions:
// Explicit null check
channelNo != null && channelNo.equals(o.getChannelNo()) // Using Objects.equals which handles nulls
Objects.equals(channelNo, o.getChannelNo()) // Using utility libraries
StringUtils.equals(channelNo, o.getChannelNo()); // Apache Commons
StrUtil.equals(channelNo, o.getChannelNo()); // HutoolAdditional Resources
Scan the QR code and reply "图书" to receive a free book on a book management system, including source code.
--- EOF
Architecture Digest
Focusing on Java backend development, covering application architecture from top-tier internet companies (high availability, high performance, high stability), big data, machine learning, Java architecture, and other popular fields.
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.