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.

Architect's Guide
Architect's Guide
Architect's Guide
Null Checks and Optional Usage in Java

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.

Original Source

Signed-in readers can open the original source through BestHub's protected redirect.

Sign in to view source
Republication Notice

This article has been distilled and summarized from source material, then republished for learning and reference. If you believe it infringes your rights, please contactadmin@besthub.devand we will review it promptly.

StringListoptionalbest-practicesnull check
Architect's Guide
Written by

Architect's Guide

Dedicated to sharing programmer-architect skills—Java backend, system, microservice, and distributed architectures—to help you become a senior architect.

0 followers
Reader feedback

How this landed with the community

Sign in to like

Rate this article

Was this worth your time?

Sign in to rate
Discussion

0 Comments

Thoughtful readers leave field notes, pushback, and hard-won operational detail here.