Skip to content

Course navigation

For teachersTopic 4.7 · Lesson kit

Wrapper Classes

  • 2 class periods
  • 45 minutes each
  • Objective 4.7.A
  • 6 downloads with keys

Downloads

  • Slides

    Speaker notes on every slide

  • Lesson plan

    2 periods of 45 minutes

  • Worksheet

    Puzzles, about 30 minutes

  • Worksheet key

    Answer key

  • Exit ticket

    End of the last period

  • Exit ticket key

    Answer key

Download all AP CSA teacher filesEvery topic's slides, lesson plan, worksheet, and exit ticket, with keys (.zip)

At a glance

Pacing
2 class periods of 45 minutes
Learning objectives
4.7.A
Essential knowledge
4.7.A.14.7.A.24.7.A.34.7.A.44.7.A.5
Materials
Projector and the Numbers in Envelopes slide deckWhiteboard and markersMini whiteboards or scrap paperIDE on every computer (Day 2)Printed Numbers in Envelopes puzzle worksheet (answer key for you) and exit ticket

45 minutes a day

Agenda

Day 145 minutes

  • Warm-up
  • Direct instruction
  • Independent practice
  • Closure
  • Activity
  1. 0:00–0:055 minWarm-upsix plus seven is…? (slide 2)
  2. 0:05–0:1712 minDirect instructionprimitive or wrapper, java.lang, Integer.MIN_VALUE and MAX_VALUE (slides 3–7)
  3. 0:17–0:3013 minDirect instructionautoboxing, unboxing, the matching wrapper, unboxing null (slides 8–12)
  4. 0:30–0:355 minActivityDay 1 pause and try — box, unbox, or neither? (slide 13)
  5. 0:35–0:427 minIndependent practicepuzzle worksheet question 2 and question 6 snippets 1–4
  6. 0:42–0:453 minClosurewhich way does the envelope go?

Day 245 minutes

  • Warm-up
  • Direct instruction
  • Guided practice
  • Closure
  • Exit ticket
  • Activity
  1. 0:00–0:044 minWarm-upthe Think First guess on the worksheet
  2. 0:04–0:139 minDirect instructionwrapper objects are immutable (slides 14–16)
  3. 0:13–0:2411 minDirect instructionparseInt and parseDouble, NumberFormatException (slides 17–19)
  4. 0:24–0:284 minActivityDay 2 pause and try — number or text? (slide 20)
  5. 0:28–0:368 minGuided practiceworksheet question 4 in the IDE, decoys included
  6. 0:36–0:404 minClosurebox it, open it, parse it (slides 21–22)
  7. 0:40–0:455 minExit ticket

Overview

This topic gives a name and a rule set to something students have half-seen since Topic 1.5: the Integer class. Day 1 covers what a wrapper object is (4.7.A.1), the Integer.MIN_VALUE and Integer.MAX_VALUE constants as starting values for the Topic 4.5 minimum and maximum algorithms, and the two automatic conversions, autoboxing (4.7.A.2) and unboxing (4.7.A.3). Day 2 covers immutability (4.7.A.1) and the two Java Quick Reference methods Integer.parseInt and Double.parseDouble (4.7.A.4, 4.7.A.5), which finally turn the text pieces from Topic 4.6 file lines into numbers.

Keep one picture running through both days, the one the deck and the study guide use: a wrapper object is a number sealed in an envelope. Autoboxing seals it, unboxing opens it, and nobody can change what is inside; arithmetic on a wrapper builds a new envelope.

Stay inside the boundary. Students know arrays, enhanced for loops, split, and reading files with Scanner and File (Topic 4.6), but not the next topic’s resizable list. You can say that some parts of Java hold objects only and that students will meet one next topic; do not name or demonstrate it. Do not use new Integer(...): the constructor is deprecated and not on the exam (worksheet question 5’s Fair Question box says the same).

Teacher note

The slides are the Numbers in Envelopes deck (22 slides); slide numbers below refer to it. Day 1 uses slides 2–13 and Day 2 uses slides 14–22. The Numbers in Envelopes puzzle worksheet (9 questions, about 30 minutes) is split by day: question 2 and question 6 snippets 1–4 need only Day 1 material; questions 1, 3, 4, 5, 7, 8, 9 and question 6 snippet 5 need Day 2 (parsing or immutability).

Demonstrations come from the topic’s examples/ folder (the same programs as the study guide, each with Open in IDE): FastestLap, WarmestZeroBug, AutoboxParameter, BoxWrongType, UnboxWiden, UnboxNull (Day 1); IntegerAlias, IntegerParameter, CompareValues, ParseRecord, ParseIntDecimal, SplitSpace (Day 2). Open them in the IDE before class so each demo is one click.

Day 1 · Warm-up: Six plus seven is…?

Show slide 2. Students write what a + b prints when a is "6" and b is "7", and how they would get 13 instead. Most see 67 right away; the second question is the hook. Take a few answers. Some will suggest a cast such as (int) a, which does not compile on a String. Do not resolve it: write “How do we turn "6" into 6?” in a corner of the board and say that it gets answered tomorrow. The slide’s hint points back to Topic 4.6: every piece of a split file line is a String, even when it looks like a number.

Day 1 · Direct instruction: A number inside an object

  1. Goals (slide 3). Read the five goals; goals 1–3 are today’s, 4–5 are Day 2’s.
  2. Primitive or wrapper? (4.7.A.1, slides 4–5). Draw the two boxes from slide 5 on the board: laps holds 12 itself; count holds a reference to an Integer object whose value is 12. Point at the capital letters: int and double are primitive types, Integer and Double are class names. Because count is a class-type variable, it can also hold null (Topic 1.13); an int never can. Ask: “Why might Java need a number packaged as an object?” Accept “some code only works with objects” and say students will meet such code next topic.
  3. java.lang (4.7.A.1, slide 5). Ask why Integer.MAX_VALUE works with no import but File needed import java.io.File; in Topic 4.6. Integer and Double are in the java.lang package, available to every program, the same as String and Math.
  4. A start that any value beats (slide 6). Students have used Integer.MAX_VALUE since Topic 1.5; now they can read it as a static constant of the Integer class (Topic 3.7). Cover the table’s right columns and have students fill in shortest after each wait before you reveal: 2147483647, 14, 6, 6, 6. The first comparison is always true, so the minimum takes a real value immediately. Run FastestLap for a second data set.
  5. Starting the maximum at 0 (slide 7). Before showing the right side, ask what the freezer program prints. Then reveal 0, a temperature that is not in the array, and the fix, Integer.MIN_VALUE, which prints -16. Run WarmestZeroBug to see the same logic error with overnight lows.

Misconception: Starting a maximum at 0

Zero feels like “nothing yet”, so students start every maximum there. It works only when some value is above 0; with all-negative data the answer is 0, a value not in the data, and the program gives no error. Make students say the rule aloud: a minimum starts at Integer.MAX_VALUE, a maximum at Integer.MIN_VALUE (or either starts at the first element). Worksheet question 5 tests exactly this choice.

Day 1 · Direct instruction: Autoboxing and unboxing

  1. Autoboxing (4.7.A.2, slides 8–9). Show Autobox.java on slide 9. Ask, “Where is the new?” There is none: when an int is assigned to an Integer variable (Integer laps = 8;) or passed to an Integer parameter (showLaps(12)), the compiler adds the code that builds the object. Same for double to Double (Double miles = 3.5;). Printing a wrapper shows its number, not an address: the output is 8 3.5 and Laps: 12. Run AutoboxParameter to show a literal and a variable both boxing at a parameter.
  2. Unboxing (4.7.A.3, slide 10). The mirror image: an Integer assigned to an int variable (int copy = stored;) or passed to an int parameter (Math.abs(stored)) is unboxed. Java also unboxes a wrapper used in arithmetic or a comparison (rate * 10), because operators work on primitive values. Have students predict the output before revealing it: -9 9 and 15.0.
  3. Only the matching wrapper (slide 11). Show only the top-left code, Double price = 5;, and ask whether it compiles. Many students will say yes, because Topic 1.5 taught that an int widens to a double. Reveal the error, int cannot be converted to Double, and the fix, 5.0. Run BoxWrongType. Then the bottom row: unboxing then widening is fine (double x = n; prints 4.0, demo UnboxWiden), but unboxing a Double into an int would narrow, so it does not compile, for the same reason int stars = 4.0; fails.
  4. Unboxing null (slide 12). Ask where this program fails: at compile time, or on which line at run time? Then reveal: Checking record prints, and the next line throws a NullPointerException. Unboxing calls a method on the object to get its number (the message names intValue()), and calling a method through null throws, just as in Topic 1.14. The compiler cannot catch it because the types are correct. Run UnboxNull.

Misconception: An int fits in a Double

Students carry the Topic 1.5 widening rule over to wrappers and expect Double price = 5; to compile. Autoboxing goes only to the matching wrapper: int to Integer, double to Double. Java will not widen and box in one step. In the other direction, an Integer unboxes to int and may then widen to double, but a Double never narrows to int. Slide 11’s four boxes are the reference; worksheet question 6 snippets 1–3 test all three cases.

Misconception: An ordinary assignment cannot crash

int next = record + 1; looks like plain arithmetic, so students expect either a compile error or the value 1. Neither happens: it compiles, then throws a NullPointerException at run time because there is no object to unbox. Ask “Is this a type problem or a value problem?” A type problem is a compile error; a value problem shows up only when the program runs.

Day 1 pause and try

Slide 13. Partners label lines 1–4 as autobox, unbox, or neither, then write the output. Give two minutes, then take answers line by line:

  • Line 1: autobox (an int into an Integer variable).
  • Line 2: unbox (tickets is used in arithmetic; the result, 37, goes into an int).
  • Line 3: autobox (a double into a Double variable).
  • Line 4: unbox (cost is used in arithmetic; left is an int that widens, which is not boxing). The output is 83.25 (2.25 × 37).

Ask anyone who wrote “neither” for line 2 or 4 which variable is a wrapper there.

Day 1 · Independent practice: Independent practice

Hand out the puzzle worksheet. Students work question 2 (label six statements autobox, unbox, or neither) and question 6 snippets 1–4 (you’re the compiler). Circulate and check row 5 of question 2: Math.max(count, 3) unboxes count because Math.max takes int parameters. Rows 3 and 6 are “neither”: row 3 is plain widening and row 6 is parseInt returning an int, which students can answer from the return type even before Day 2.

Teacher note

Snippet 5 of question 6 uses Integer.parseInt; tell students to leave it for Day 2. The rest of the worksheet is Day 2 homework.

Day 1 · Closure: Closure

Cold-call two quick ones: “Integer n = 7; — into the envelope or out?” (into: autoboxing) and “int m = n; — into or out?” (out: unboxing). Then: “Which of these can hold null: int or Integer?” (Integer).

Day 2 · Warm-up: Will the other one see it?

Point students to the Think First box on the worksheet (page 1, below question 1): two Integer variables refer to the same object, and you add 5 through one of them. Does the other see the new number? Students write a guess in the margin and commit to it. Take a quick hand vote and leave the tally on the board. Remind them of Topic 3.6: a method that received a Player could change it through a mutator, and the caller saw the change. Will an Integer behave the same way?

Day 2 · Direct instruction: Sealed for good

  1. Immutable (4.7.A.1, slides 14–15). An Integer or Double object can never change after it is created; neither class has a method that changes the stored number. Students know the word from String in Topic 1.15. Show the code on slide 15 and ask for the output before revealing it. Then walk through points = points + 2; step by step on the board: unbox 7, add 2, box 9 into a new object, make points refer to it. saved still refers to the old object, so the output is 9 then 7. Settle the warm-up vote: the other variable does not see the change. Run IntegerAlias for a second case.
  2. A method cannot change your Integer (slide 16). Ask what Tip.java prints before revealing it. bill gets a copy of the reference; bill = bill + 5; builds a new object and changes only the parameter (Topic 3.6), so the output is Inside: 25 and In main: 20. Run IntegerParameter. Ask, “How could main get 25?” Collect “return it”, and write total = addTip(total); with addTip returning an Integer. That is exactly worksheet question 9’s fix, so do not show the full program.
  3. Comparing wrapper values. Briefly, without a slide: when both sides of == are Integer objects, == compares references, as with two String variables in Topic 2.6, so it is not a reliable way to compare their numbers. Compare with equals, or unbox into int variables first. Run CompareValues. Keep this to two minutes; the worksheet does not test it.

Misconception: A method can update the caller's Integer

Because an Integer is an object, students expect it to behave like a Player: pass it in, change it, and the caller sees the change. Two facts block that: the object is immutable, so there is nothing to call that changes it, and assigning to the parameter changes only the parameter. The fix is always to return the new value and assign it in the caller. Worksheet question 9 tests this directly.

Misconception: The alias follows along

After Integer saved = points;, students believe both variables are now linked forever, so saved will show the new number. They are linked only until one of them is assigned a new object, and every arithmetic update on a wrapper does exactly that. Have students draw slide 15’s two snapshots themselves: after the assignment, two arrows to one envelope; after the update, two envelopes. Worksheet question 7’s lie is this misconception.

Day 2 · Direct instruction: Text into numbers

  1. The Quick Reference methods (4.7.A.4, 4.7.A.5, slides 17–18). Return to the Day 1 corner of the board: “How do we turn "6" into 6?” Answer: Integer.parseInt("6"). Show the two headers on slide 18 and point out that students will have them on the exam’s Java Quick Reference. Both are static methods (Topic 3.7), called through the class name, never through an object. parseInt returns an int and parseDouble returns a double.
  2. One record from a file (slide 18). Students know split from Topic 4.6. Cover the output and the table, then have students fill in the type and value of parts[1], points, and hours. Reveal: "42" is a String, points is the int 42, hours is the double 3.5. The output is Lee: 43 (the parentheses make + 1 add before joining) and 12.0 (42 / 3.5). Run ParseRecord for a second record.
  3. parseInt does not round (slide 19). Ask what Integer.parseInt("2.75") gives. Students who remember casts from Topic 1.5 say 2. Reveal: the program prints Reading miles, then throws a NumberFormatException. Walk the table at the bottom of the slide: "75" works for both methods, "2.75" works only for parseDouble, and " 14" (a leading space) crashes both. The compiler cannot catch any of these, because any String is a legal argument. Run ParseIntDecimal, then SplitSpace to show where a stray space comes from: splitting Lee, 14 on "," instead of ", " (the worksheet’s Watch Out box after question 3 repeats this).

Misconception: parseInt rounds or truncates like a cast

Students expect Integer.parseInt("7.5") to give 7, the way (int) 7.5 does. A cast converts a number; parseInt reads text, and text with a decimal point is not a whole number, so it throws a NumberFormatException. Rule to teach: choose the method that matches the text. If the text could have a decimal point, use parseDouble.

Misconception: Wrapping a number changes how division works

Worksheet question 1 divides two Integer values: (a + b) / 2. Students expect objects to divide “properly” and write 6.5. Unboxing gives int values, and two int values divide with truncation (Topic 1.3); the result 6 is widened to 6.0 only afterward. If this comes up, contrast total / count with 1.0 * total / count (the study guide’s review question 17).

Day 2 pause and try

Slide 20. Students write the three lines of output on mini whiteboards, deciding first whether each + joins or adds. Reveal:

  • 123: parseInt gives the int 12, but "3" is a String, so + joins.
  • 15: both operands are int values, so + adds.
  • 0.5: parseDouble("4") is 4.0, and 4.0 / 8 is a double division.

Day 2 · Guided practice: Code tiles in the IDE

Pairs do worksheet question 4 (the snack bar code tiles) on paper, then type their program into the IDE under the given prices array and run it to check for Total: 8.5. Then each pair tries the two decoy tiles, one at a time, and records what happens:

  1. Double total = 0; instead of Double total = 0.0; — does not compile: an int cannot box into a Double.
  2. Integer.parseInt(p) instead of Double.parseDouble(p) — compiles, then throws a NumberFormatException on "2.50".

Debrief in one minute: one decoy is a type problem the compiler catches, the other is a value problem that shows up only at run time. Point out what happens on each pass of the working loop: total is unboxed, the sum is computed, and the result is boxed into a new Double.

Teacher note

If the IDE is not available, run this as a whole-class demo: you type, the class calls out which tile comes next, and you try each decoy on the projector.

Day 2 · Independent practice: Independent practice

The rest of the worksheet is homework, about 25 minutes: question 1 (you’re the JVM), question 3 (the int versus Integer face-off), question 5 (snippet pool: the best lemonade day with Integer.MIN_VALUE and parseInt), question 6 snippet 5, question 7 (two truths and a lie), question 8 (who am I?), and question 9 (one-line fix). Question 7 settles the Think First guess from the warm-up; ask students to compare it with what they wrote in the margin.

Day 2 · Closure: Closure and exit ticket

Show slide 21 and ask pairs to quiz each other on two of the six terms. Then slide 22: partners explain, step by step, what happens when Java runs total = total * 2; on an Integer total. Take one answer and fill in the sentence starter: first Java unboxes total, then it doubles it, then it autoboxes the result into a new Integer object.

Give the exit ticket (about five minutes). Score each question separately: question 1 checks where autoboxing and unboxing happen (4.7.A.2, 4.7.A.3), question 2 parsing and immutability (4.7.A.1, 4.7.A.4), and question 3 choosing the right parse method and the NumberFormatException (4.7.A.4, 4.7.A.5). Re-teach the weakest one at the start of Topic 4.8.

Exit ticket

Question 1 · Multiple choice

The program prints Total: 10.0. Which description of lines 5, 7, and 8 is correct?

ExitConvert.java
public class ExitConvert
{
    public static void main(String[] args)
    {
        Double price = 2.5;
        int quantity = 4;
        double cost = price * quantity;
        showTotal(cost);
    }

    public static void showTotal(Double total)
    {
        System.out.println("Total: " + total);
    }
}
  1. Line 5 unboxes; line 7 autoboxes; line 8 unboxes.
  2. Line 5 autoboxes; line 7 does neither; line 8 does neither.
  3. Line 5 autoboxes; line 7 unboxes; line 8 autoboxes.
  4. Line 5 autoboxes; line 7 unboxes; line 8 does neither.
Check your reasoning

C. Line 5 assigns the double 2.5 to a Double variable: autoboxing. Line 7 uses price in arithmetic, so it is unboxed to 2.5 (quantity is an int that widens; that is not boxing). Line 8 passes the double cost to showTotal, whose parameter on line 11 is a Double: autoboxing.

  • A reverses every direction: boxing goes from primitive to object, unboxing from object to primitive.
  • B misses that price * quantity needs a primitive, and that a method parameter is a place where boxing happens.
  • D misses the parameter: cost is a double and the parameter is a Double, so the value is boxed on line 8.

Question 2 · Multiple choice

What does this code print?

String[] parts = "Kai,12".split(",");
Integer points = Integer.parseInt(parts[1]);
Integer saved = points;
points = points + 3;
System.out.println(parts[1] + 3);
System.out.println(points + " " + saved);
  1. 123 on the first line, then 15 12
  2. 15 on the first line, then 15 12
  3. 123 on the first line, then 15 15
  4. Nothing: line 4 does not compile, because + cannot be used on an Integer object
Check your reasoning

A.

  • Line 1: parts[1] is the String "12".
  • Line 2: Integer.parseInt returns the int 12, which is autoboxed into an Integer.
  • Line 3: saved refers to the same object as points.
  • Line 4: points is unboxed, 12 + 3 is 15, and 15 is boxed into a new object. Only points moves to it; saved still refers to the object holding 12, because Integer objects are immutable.
  • Line 5: parts[1] is still the String "12", so + joins: "123".

B thinks parsing changed the string into a number, but parseInt returns a new int and leaves parts[1] as "12". C thinks line 4 changed the shared object, but it makes a new Integer and moves only points. D misses unboxing: Java unboxes points for the arithmetic and boxes the result, so line 4 compiles.

Question 3 · Multiple choice

A file line Ana,4.5 is split on ",", and a student writes int hours = Integer.parseInt(parts[1]);. Which statement is correct?

  1. It does not compile, because parts[1] holds a decimal number.
  2. It compiles, then throws a NumberFormatException when it runs; double hours = Double.parseDouble(parts[1]); fixes it.
  3. It compiles and stores 4, because parseInt drops the decimal part the way an (int) cast does.
  4. It compiles, then throws a NumberFormatException when it runs; double hours = Integer.parseInt(parts[1]); fixes it.
Check your reasoning

B. parseInt accepts any String and returns an int, so the statement compiles. When it runs, "4.5" is not a whole number, so parseInt throws a NumberFormatException. Double.parseDouble reads "4.5" and returns the double 4.5.

A expects the compiler to check the text, but it cannot know what a string will hold while the program runs. C treats parseInt like a cast; it does not round or truncate, it throws. D changes only the variable’s type: Integer.parseInt still gets "4.5" and still throws.