Unit 1 Cycle 1 Day 19: Autoboxing and Unboxing

Unit 1 Foundation (Cycle 1) Day 19 of 28 Foundation

Autoboxing and Unboxing

Section 1.12 — Wrapper Classes

Key Concept

String methods can be chained together because each method returns a new String object. For example, s.substring(1).toUpperCase() first extracts a substring, then converts it to uppercase. The AP exam tests method chaining with substring(), indexOf(), and length(). A key pattern is extracting the last character: s.substring(s.length() - 1). When tracing chained calls, evaluate from left to right, treating each intermediate result as the new calling object. Watch for StringIndexOutOfBoundsException when indices are invalid.

Consider the following code segment.

Integer x = 10; int y = x; Integer z = y + 5; System.out.println(x + " " + y + " " + z);

What is printed as a result of executing the code segment?

Answer: (A) 10 10 15

Java automatically converts between primitives and wrapper classes:

Line 1 (autoboxing): Integer x = 10; automatically wraps the int 10 into an Integer object.

Line 2 (unboxing): int y = x; automatically extracts the int value from the Integer object.

Line 3 (autoboxing): y + 5 evaluates to the int 15, which is autoboxed into a new Integer.

Output: 10 10 15

Why Not the Others?

(B) Java supports autoboxing: automatically converting int to Integer. This has been valid since Java 5.

(C) Java supports unboxing: automatically converting Integer to int. No explicit casting is required.

(D) The expression y + 5 produces an int, which Java autoboxes to Integer before assignment. This is valid.

Common Mistake

Autoboxing and unboxing happen automatically in Java. int values can be assigned to Integer variables and vice versa without explicit casting. However, Integer objects can be null, which would cause a NullPointerException during unboxing.

AP Exam Tip

Autoboxing is valid for all wrapper-primitive pairs on the AP exam: Integer/int and Double/double. The AP exam tests whether you know this is legal, and also tests the == trap with wrapper objects.

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.