Hidden Traps in Java’s JDK: Avoid These Common Pitfalls
This article reveals frequent JDK pitfalls such as missing null checks in String.valueOf, fragile Integer.parseInt conversions, BigDecimal division errors, unmodifiable Collections.emptyList, and unsafe list iteration, providing concrete code examples and safe handling recommendations for Java developers.
JDK provides essential core classes for Java development, but many of its methods lack null checks and can throw unexpected exceptions, leading to serious bugs if not handled carefully.
1. The String.valueOf() trap
When a method returns the literal string "null" instead of a null reference, a simple null‑check passes, causing messages like "尊敬的\"null\"你好" to be sent. The fix is to verify the object before calling String.valueOf.
Map<String, Object> userInfo = userService.getUserInfoById(userId);
Object userNameObject = userInfo.get("name");
String userName = String.valueOf(userNameObject);
if (userName != null && userName.length() > 0) {
String message = getMessage(userName);
smsService.send(message);
}2. Integer.parseInt() is picky
Parsing strings like "120.0" with Integer.parseInt throws NumberFormatException. Use BigDecimal for numeric strings that may contain decimals, or the Hutool NumberUtil.parseInt() method which tolerates various formats.
3. BigDecimal division pitfalls
Dividing with BigDecimal can raise ArithmeticException when the result is a non‑terminating decimal. Always specify a scale and rounding mode.
BigDecimal a = new BigDecimal("1");
BigDecimal b = new BigDecimal("3");
BigDecimal result = a.divide(b, 10, RoundingMode.HALF_UP); // keep 10 decimal places4. Collections.emptyList() is read‑only
The list returned by Collections.emptyList() cannot be modified; attempts to add or remove elements throw UnsupportedOperationException. Use a mutable list when you need to modify the collection.
public List<String> getUserNameList(String userId) {
List<String> resultList = Collections.emptyList();
try {
resultList = userDao.getUserName(userId);
} catch (Exception ex) {
logger.info(ex);
}
return resultList;
}5. Removing elements while iterating a list
Direct removal during iteration causes ConcurrentModificationException. Use an Iterator and its remove() method.
List<Integer> list = new ArrayList<>();
list.add(1);
list.add(2);
list.add(3);
list.add(4);
Iterator<Integer> iterator = list.iterator();
while (iterator.hasNext()) {
Integer i = iterator.next();
if (i == 2) {
iterator.remove();
}
}6. Other useful notes
When comparing BigDecimal values, prefer compareTo over equals because equals also checks scale.
MySQL subtraction with a NULL operand yields NULL; wrap columns with IFNULL(col,0) to avoid unexpected null results.
When splitting strings with the pipe character, escape it (e.g., "\\|\\|") because String.split treats the argument as a regular expression.
Conclusion
JDK methods often omit null checks and throw exceptions directly, so developers must read source code, add proper validations, and handle errors proactively to prevent small issues from causing major business impacts.
Signed-in readers can open the original source through BestHub's protected redirect.
This article has been distilled and summarized from source material, then republished for learning and reference. If you believe it infringes your rights, please contactand we will review it promptly.
Programmer DD
A tinkering programmer and author of "Spring Cloud Microservices in Action"
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.
