Unit 1 Cycle 1 Day 19: Autoboxing and Unboxing
Share
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.
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.