4.07 Wrapper Classes
Use wrapper classes to convert between primitive values and objects, parse data, and work with useful constants and methods.
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.
Your mission and learning path
Run the club snack shop: turn text receipts into numbers, calculate totals, and return a wrapper object for the sales system.
Start with your experience: Why does “3” + “2” behave differently from 3 + 2? Tell a partner what you expect before running anything.
Success looks like: You distinguish parsing, boxing, and unboxing; explain immutable wrappers; and total an order without confusing text with numeric data.
| Learning design step | What you do | Evidence you keep |
|---|---|---|
| Understand the learner | Compare your prediction with a partner’s. Name what feels confusing. | One question in your notes |
| Define the goal | Read the success criteria and pick the skill you need to practice. | A specific goal |
| Try a small solution | Run an example, change one input, and predict the effect. | Before/after output |
| Test your idea | Attempt the popcorn task, then use the homework checks. | Expected versus actual results |
| Get feedback and revise | Have a partner try one new input. Explain and fix any mismatch. | One comment, your change, and the rerun |
Suggested pace: 5 minutes to predict, 15 to explore, 10 for partner practice, and 5 for the exit ticket; finish the homework afterward.
Using the runners: Click Run below a challenge. Each editor is a separate complete Java program; it does not remember variables from another editor. Edit the code, then run again. Use Copy Code to keep your work. In a Java notebook, keep the final ClassName.main(null); call; in a .java file, remove that final call and run the class normally.
1. 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.
2. 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.
3. 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.
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:
4. 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;.
5. 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.
6. 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.
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:
7. 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.
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);
Publish your homework and check it as a student
- In your own portfolio, create
_notebooks/homework/2026-09-21-4-7-homework.ipynb. Choose a Java kernel. Copy your completed homework runner into a code cell, including the imports, class, and finalmain(null)call. - Add a raw cell first with the template below. Replace
your-github-idandYour Name; keep your own unique permalink.
---
layout: post
title: "4.7 Homework"
description: "My predictions, Java solution, test results, and revision."
author: Your Name
categories: [Java, Homework]
lesson_language: Java
codemirror: true
permalink: /homework/your-github-id/4-7/
---
- Add Markdown sections named Prediction, Solution, Tests, and Feedback and revision. Annotate the parsing, boxing, and unboxing steps, and keep the immutable-wrapper prediction from class.
- Run all cells from a fresh kernel. Keep the printed output. Include the supplied checks and one test you designed, with expected and actual results. Fix failing checks before submitting.
- Commit and publish in your portfolio. Open the published homework page and run its editor again. Check that the code, outputs/evidence, and your name are visible. If you get a 404, check the build and the exact permalink before submitting.
- Use the lesson’s submission form when available: sign in, paste your published homework URL, and include the evidence below. If your class uses a different submission destination, use the one your teacher provides. Do not submit the lesson’s URL as your homework.
Lesson: 4.7
Homework URL:
Popcorn result:
Supplied checks passed / total:
My extra test: input / expected / actual
Partner feedback:
What I changed and the rerun result:
Self-check rubric (1 point): popcorn work with reasoning 0.2; completed homework and explanation 0.4; supplied tests plus your own boundary test 0.2; working published link and feedback/revision evidence 0.2. These are the lesson’s proposed criteria; follow any changes your teacher gives you.
If every check already passes, revise an explanation or add a stronger test after peer feedback. Report what actually happened; do not invent a peer review or a test result.
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.
Submit Assignment
Need to update a submission later? Open the submissions dashboard.