Backend Development 7 min read

Why Java’s Ternary Operator Can Trigger NullPointerException with Autoboxing

This article explains how the combination of Java's ternary operator and automatic boxing/unboxing can unintentionally cause a NullPointerException, demonstrates the issue with decompiled code, and provides a safe coding pattern to avoid the runtime error.

macrozheng
macrozheng
macrozheng
Why Java’s Ternary Operator Can Trigger NullPointerException with Autoboxing

Recently Alibaba released the new "Taishan" version of its Java Development Manual, which mentions a common pitfall involving the ternary operator and autoboxing that can cause a NullPointerException (NPE).

1. Ternary Operator

The conditional expression

b?x:y

evaluates the condition

b

first; if true, it evaluates

x

, otherwise

y

. Only one of

x

or

y

is evaluated, and the operator is right‑associative.

2. Autoboxing and Unboxing

Since Java 5, primitive types can be automatically boxed into their wrapper classes and unboxed back. For example,

Integer i = 100;

is compiled to

Integer i = Integer.valueOf(100);

.

3. Problem Review

The following code often appears in projects:

<code>Map<String, Boolean> map = new HashMap<>();
Boolean b = (map != null ? map.get("test") : false);
</code>

When

map.get("test")

returns

null

, the ternary expression forces unboxing of a

null
Boolean

, leading to an NPE.

4. Analysis

Decompiling the code shows the compiler generates:

<code>HashMap hashmap = new HashMap();
Boolean b = Boolean.valueOf(hashmap == null ? false : ((Boolean)hashmap.get("test")).booleanValue());
</code>

The unboxing step

((Boolean)hashmap.get("test")).booleanValue()

invokes

booleanValue()

on

null

, which throws the exception.

The Java Language Specification (JLS 15.25) states that if one operand is primitive and the other is its boxed type, the result type is the primitive, causing the automatic unboxing.

5. Solution

Ensure both operands of the ternary operator are reference types, e.g.:

<code>Map<String, Boolean> map = new HashMap<>();
Boolean b = (map != null ? map.get("test") : Boolean.FALSE);
</code>

This prevents unboxing of a

null

wrapper and eliminates the NPE.

backendJavaautoboxingnullpointerexceptionternary operator
macrozheng
Written by

macrozheng

Dedicated to Java tech sharing and dissecting top open-source projects. Topics include Spring Boot, Spring Cloud, Docker, Kubernetes and more. Author’s GitHub project “mall” has 50K+ stars.

0 followers
Reader feedback

How this landed with the community

login 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.