AP CSA Unit 1 Day 17: Wrapper Null Safety

Unit 1 Advanced (Cycle 2) Day 17 of 28 Advanced

Wrapper Classes and Null Safety

Section 1.12 — Wrapper Classes

Key Concept

Wrapper class null safety is critical because unboxing a null wrapper throws a NullPointerException. If Integer x = null, then int y = x crashes at runtime. The AP exam tests this in conditional expressions, method returns, and array elements. Safe patterns include checking for null before unboxing, using the ternary operator (x != null ? x : 0), and understanding that comparison operators like < also trigger unboxing. A null Integer cannot be compared with <, >, or used in arithmetic.

Consider the following code segment.

Integer a = null; Integer b = 10; int c = b; System.out.println(c); int d = a;

What happens when this code segment is executed?

Answer: (A) It prints 10 then throws a NullPointerException.

Trace execution order:

Line 1: Integer a = null is valid. Wrapper objects can be null.

Line 2: Integer b = 10 autoboxes to an Integer object.

Line 3: int c = b unboxes to 10. Valid.

Line 4: Prints 10.

Line 5: int d = a tries to unbox null. Java calls a.intValue() on a null reference, throwing NullPointerException.

Why Not the Others?

(B) Wrapper types are objects and can hold null. This is one key difference between Integer and int.

(C) null does not unbox to 0. Unboxing a null wrapper throws NullPointerException. Only primitive int has a default value of 0 (as an instance variable).

(D) The exception occurs on line 5, not before. Lines 1-4 execute successfully, printing 10 before the crash.

Common Mistake

Wrapper types can be null but primitives cannot. Unboxing null causes a NullPointerException at runtime, not a compile error. This is a dangerous pitfall because the code compiles fine but crashes when run.

AP Exam Tip

When you see Integer variables, always consider whether they could be null. Unboxing a null wrapper is a runtime error, not a compile error. The AP exam tests this distinction.

Review this topic: Section 1.12 — Wrapper Classes • Unit 1 Study Guide

More Practice

Back to blog

Leave a comment

Please note, comments need to be approved before they are published.