4.07 Wrapper Classes
Use wrapper classes to convert between primitive values and objects, parse data, and work with useful constants and methods.
- Reference Guide
- Learning targets
- Warm-up: same digits, different types
- Wrapping a value
- Predict, pair, explain: immutable objects
- Code Runner Challenge
- Your response
- Convert numeric text: parsing
- Partner card sort
- Popcorn hack: a receipt from text
- Code Runner Challenge
- Your solution
- Exit ticket
- Homework: close the snack shop register
- Code Runner Challenge
- References and next steps
Reference Guide
From the College Board: This lesson aligns with AP CSA Unit 4, Topic 4.7: Wrapper Classes in the AP Computer Science A Course and Exam Description (College Board, 2025). The guide below summarizes the concepts in our own words.
Practice distinguishing parsing, boxing, and unboxing when values move between text, primitives, and objects.
| Concept | What to remember |
|---|---|
| Wrapper class | Integer and Double represent numeric values as objects. |
| Autoboxing | Java converts a primitive to its wrapper, as in Integer n = 8;. |
| Unboxing | Java extracts a primitive value, as in int value = n;. |
| Parsing | Integer.parseInt("8") returns an int; Double.parseDouble("2.5") returns a double. |
| Immutability | Reassigning a wrapper variable does not change the original object’s value. |
Keep this guide open as you work through the examples and homework. Full references are also listed at the end of the lesson.
4.7 — Wrapper Classes
AP CSA · Unit 4: Data Collections
A file gives you the text "12", a calculation needs the number 12, and a collection may need an Integer object. These values look similar, but they play different roles.
Learning targets
Distinguish primitives, wrapper objects, and numeric Strings; trace autoboxing and unboxing; explain wrapper immutability; and use Integer.parseInt and Double.parseDouble.
Before you start: primitive/reference types, assignment, methods, and String concatenation. ArrayList knowledge is not required.
Try it: Predict the answer, record your work in your notes, and compare with a partner. Open each answer reveal after attempting the activity.
Warm-up: same digits, different types
int count = 12;
Integer boxedCount = 12;
String textCount = "12";
With a partner, identify the primitive, the wrapper reference, and the String reference. Predict both results:
System.out.println(count + 3);
System.out.println(textCount + 3);
Check your reasoning
count is an int primitive. boxedCount refers to an Integer wrapper object. textCount refers to a String.
The output is 15, then 123. The first expression adds integers. The second concatenates text and the String representation of 3.
Wrapping a value
| Primitive type | Wrapper class | Example assignment |
|---|---|---|
int |
Integer |
Integer score = 95; |
double |
Double |
Double price = 4.5; |
Integer and Double are in java.lang, so you do not need to import them. Wrappers let numeric values participate where an object is required. For example, the next topic’s ArrayList<Integer> stores Integer references; ArrayList<int> is not a valid generic type.
Name the direction
int / double ── autoboxing ──> Integer / Double
int / double <── unboxing ──── Integer / Double
int original = 8;
Integer boxed = original; // autoboxing: int -> Integer
int restored = boxed; // unboxing: Integer -> int
Double fee = 2.5; // autoboxing: double -> Double
double total = fee + 1.0; // unboxing for arithmetic
These conversions also occur at method calls. Assume these methods are declared inside the surrounding class:
public static int addOne(int n) {
return n + 1;
}
public static int readWrapped(Integer n) {
int value = n;
return value;
}
You decide: Which conversion happens when addOne(boxed) is called? Which happens when readWrapped(8) is called? Is there a second conversion inside readWrapped?
Check your reasoning
addOne(boxed) unboxes the Integer argument to match the int parameter and returns 9.
readWrapped(8) boxes 8 to match the Integer parameter. Inside that method, assigning n to the primitive variable value unboxes it. The method returns the primitive 8.
Predict, pair, explain: immutable objects
Integer first = 10;
Integer second = first;
first = first + 5;
System.out.println(first);
System.out.println(second);
Vote before revealing: A. 15, 15 · B. 15, 10 · C. 10, 10 · D. compilation error.
Integer and Double objects are immutable: the value inside an existing wrapper object cannot be changed. A variable can still be assigned a different reference.
Check your reasoning
B. The output is 15 and then 10.
| Step | first refers to a wrapper holding | second refers to a wrapper holding |
|---|---|---|
| After both declarations | 10 | 10 |
After first = first + 5 |
15 | 10 |
Java unboxes first, adds 5, boxes the result, and assigns the resulting reference to first. It does not change the original wrapper that second still references. Do not assume every boxing operation allocates a brand-new object; the essential point is that the old object’s value is unchanged.
Draw it: Draw arrows from first and second to their objects before and after reassignment. Explain why “the object changed” is an inaccurate description.
Predict 15, 10, 15, and 9; explain each conversion before running.
public class SnackShopTypes {
public static void main(String[] args) {
Integer first = 10; // autoboxing
Integer second = first;
first = first + 5; // unbox, add, box a new value
int count = first; // unboxing
Integer delivery = Integer.parseInt("9"); // parse, then box
System.out.println(first);
System.out.println(second);
System.out.println(count);
System.out.println(delivery);
System.out.println("int range: " + Integer.MIN_VALUE + " to " + Integer.MAX_VALUE);
}
}
Code Runner Challenge
Predict 15, 10, 15, and 9; explain each conversion before running.
View IPYNB Source
// CODE_RUNNER: Predict 15, 10, 15, and 9; explain each conversion before running.
public class SnackShopTypes {
public static void main(String[] args) {
Integer first = 10; // autoboxing
Integer second = first;
first = first + 5; // unbox, add, box a new value
int count = first; // unboxing
Integer delivery = Integer.parseInt("9"); // parse, then box
System.out.println(first);
System.out.println(second);
System.out.println(count);
System.out.println(delivery);
System.out.println("int range: " + Integer.MIN_VALUE + " to " + Integer.MAX_VALUE);
}
}
SnackShopTypes.main(null);
Your response
- My vote and reasoning:
- Autoboxing example in my own words:
- Unboxing example in my own words:
- Why
secondkeeps its value:
Convert numeric text: parsing
Text read from a file can look numeric while still being a String. Parsing interprets that text as a numeric value.
| Expression | Return type | Value |
|---|---|---|
Integer.parseInt("24") |
int |
24 |
Integer.parseInt("-3") |
int |
-3 |
Double.parseDouble("2.75") |
double |
2.75 |
Call these static methods on the class name. Parsing is not autoboxing: parsing starts with a String; autoboxing starts with a primitive.
String quantityText = "4";
String priceText = "2.5";
int quantity = Integer.parseInt(quantityText);
double price = Double.parseDouble(priceText);
Double receiptTotal = quantity * price;
System.out.println(receiptTotal);
Pause: Find two parsing operations and one boxing operation. What prints?
Check your reasoning
parseInt produces primitive 4; parseDouble produces primitive 2.5. Multiplication produces primitive 10.0, which is boxed when assigned to receiptTotal. The output is 10.0.
Find the mistake
Treat these lines as separate attempts:
int a = Integer.parseInt("3.5");
Integer b = "7";
Double c = 7;
Reveal repairs and explanations
parseInt("3.5")compiles but fails at runtime withNumberFormatException: decimal-point text does not represent anint. For a decimal result, usedouble a = Double.parseDouble("3.5");.Integer b = "7";fails to compile. UseInteger b = Integer.parseInt("7");: parsing first, boxing second.Double c = 7;fails to compile: theintliteral is not automatically widened and then boxed as aDoublein this assignment. UseDouble c = 7.0;.
Partner card sort
Label each line parsing, boxing, unboxing, more than one, or none. Explain the direction of each conversion.
String text = "6"; // A
int amount = Integer.parseInt(text); // B
Integer saved = amount; // C
int copied = saved; // D
Double decimal = Double.parseDouble("6.5"); // E
String label = "Total: " + text; // F
Check your reasoning
A: none. B: parsing. C: boxing. D: unboxing. E: parsing followed by boxing. F: none of the listed numeric conversions; it is String concatenation.
Popcorn hack: a receipt from text
A record has the format quantity,unitPrice, such as "3,2.5".
Write receiptTotal(String record) returning a Double. Split the record, parse each field, multiply, and return the result. Label where boxing occurs.
Contract: Exactly two valid numeric fields, no extra spaces or commas; quantity is a nonnegative integer and unit price is a nonnegative decimal. No currency formatting is required.
public static Double receiptTotal(String record) {
// Split, parse, multiply, return.
}
| Call | Expected numeric result |
|---|---|
receiptTotal("3,2.5") |
7.5 |
receiptTotal("0,4.0") |
0.0 |
receiptTotal("2,1.25") |
2.5 |
Reveal a solution after writing yours
public static Double receiptTotal(String record) {
String[] fields = record.split(",");
int quantity = Integer.parseInt(fields[0]);
double unitPrice = Double.parseDouble(fields[1]);
double total = quantity * unitPrice;
return total; // autoboxing to match the Double return type
}
Self-check: correct field indexes, both parsing methods, numeric multiplication, and a return compatible with Double. Returning fields[0] + fields[1] would concatenate Strings instead of multiplying numbers.
Complete receiptTotal, then explain where parsing and boxing occur.
public class ReceiptPractice {
public static Double receiptTotal(String record) {
// TODO: Split quantity,unitPrice; parse both fields; return the product.
return -1.0;
}
public static void main(String[] args) {
String[] records = {"3,2.5", "0,9.99", "2,1.25"};
double[] expected = {7.5, 0.0, 2.5};
for (int i = 0; i < records.length; i++) {
Double result = receiptTotal(records[i]);
boolean pass = result != null && Math.abs(result - expected[i]) < 0.000001;
System.out.println((pass ? "PASS" : "FAIL") + " " + records[i]
+ ": expected " + expected[i] + ", actual " + result);
}
}
}
Code Runner Challenge
Complete receiptTotal, then explain where parsing and boxing occur.
View IPYNB Source
// CODE_RUNNER: Complete receiptTotal, then explain where parsing and boxing occur.
public class ReceiptPractice {
public static Double receiptTotal(String record) {
// TODO: Split quantity,unitPrice; parse both fields; return the product.
return -1.0;
}
public static void main(String[] args) {
String[] records = {"3,2.5", "0,9.99", "2,1.25"};
double[] expected = {7.5, 0.0, 2.5};
for (int i = 0; i < records.length; i++) {
Double result = receiptTotal(records[i]);
boolean pass = result != null && Math.abs(result - expected[i]) < 0.000001;
System.out.println((pass ? "PASS" : "FAIL") + " " + records[i]
+ ": expected " + expected[i] + ", actual " + result);
}
}
}
ReceiptPractice.main(null);
Your solution
// Write receiptTotal here.
- The primitive values produced by parsing:
- The line where boxing occurs:
- My additional input and expected result:
Exit ticket
- What primitive type does
Double.parseDouble("8.5")return? - Identify every conversion in
Integer number = Integer.parseInt("9");. - Why does
Integer score = 4; score = score + 1;not contradict immutability? - Predict
System.out.println("8" + 2);andSystem.out.println(Integer.parseInt("8") + 2);.
Exit-ticket key
double.- The String is parsed into an
int; that primitive is boxed into anIntegerfor assignment. - The variable is reassigned after unboxing, addition, and boxing; the previous wrapper object’s value is unchanged.
82, then10.
Homework: close the snack shop register
Write Double orderTotal(String[] records). Each valid record contains quantity,unitPrice. Parse the quantity as int and price as double, accumulate with a primitive double, then return the total as a Double. A nonnull empty array returns 0.0; no record is null or malformed, and numeric inputs are nonnegative and within range.
Keep all five supplied tests. Your explanation must point to parsing and autoboxing in your method and unboxing in the test’s subtraction. For the decimal-price case, the check uses a small tolerance because double arithmetic may not represent decimal amounts exactly. This is a type-conversion exercise; production currency systems need a deliberate rounding policy.
The starter is runnable but prints FAIL until you complete orderTotal. Do not change the expected values. Add one independent test such as a zero-priced item or an order with three records.
Implement orderTotal and explain the Double return value. Run all five checks.
public class SnackShopHomework {
public static Double orderTotal(String[] records) {
// TODO: Each record is quantity,unitPrice. Return their combined total.
// Inputs are valid, nonnegative, nonnull; an empty array returns 0.0.
return -1.0;
}
public static void check(String label, String[] records, double expected) {
Double actual = orderTotal(records);
boolean pass = actual != null && Math.abs(actual - expected) < 0.000001;
System.out.println((pass ? "PASS" : "FAIL") + " " + label
+ ": expected " + expected + ", actual " + actual);
}
public static void main(String[] args) {
check("one receipt", new String[] {"3,2.5"}, 7.5);
check("two receipts", new String[] {"3,2.5", "2,1.25"}, 10.0);
check("zero quantity", new String[] {"0,9.99"}, 0.0);
check("empty order", new String[] {}, 0.0);
check("decimal price", new String[] {"3,0.1"}, 0.3);
}
}
Code Runner Challenge
Implement orderTotal and explain the Double return value. Run all five checks.
View IPYNB Source
// CODE_RUNNER: Implement orderTotal and explain the Double return value. Run all five checks.
public class SnackShopHomework {
public static Double orderTotal(String[] records) {
// TODO: Each record is quantity,unitPrice. Return their combined total.
// Inputs are valid, nonnegative, nonnull; an empty array returns 0.0.
return -1.0;
}
public static void check(String label, String[] records, double expected) {
Double actual = orderTotal(records);
boolean pass = actual != null && Math.abs(actual - expected) < 0.000001;
System.out.println((pass ? "PASS" : "FAIL") + " " + label
+ ": expected " + expected + ", actual " + actual);
}
public static void main(String[] args) {
check("one receipt", new String[] {"3,2.5"}, 7.5);
check("two receipts", new String[] {"3,2.5", "2,1.25"}, 10.0);
check("zero quantity", new String[] {"0,9.99"}, 0.0);
check("empty order", new String[] {}, 0.0);
check("decimal price", new String[] {"3,0.1"}, 0.3);
}
}
SnackShopHomework.main(null);
References and next steps
- College Board AP Computer Science A Course and Exam Description, effective fall 2025 — Topic 4.7; use the topic heading to find the learning objectives and exam scope.
- Oracle: Integer —
parseInt,MIN_VALUE, andMAX_VALUE. - Oracle: Double —
parseDoubleand wrapper behavior. - Java lesson catalog — return to the class’s lesson collection.