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
- Goals (slide 3). Read the five goals; goals 1–3 are today’s, 4–5 are Day 2’s.
- Primitive or wrapper? (4.7.A.1, slides 4–5). Draw the two boxes from slide 5 on the board:
lapsholds 12 itself;countholds a reference to anIntegerobject whose value is 12. Point at the capital letters:intanddoubleare primitive types,IntegerandDoubleare class names. Becausecountis a class-type variable, it can also holdnull(Topic 1.13); anintnever 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. - java.lang (4.7.A.1, slide 5). Ask why
Integer.MAX_VALUEworks with no import butFileneededimport java.io.File;in Topic 4.6.IntegerandDoubleare in thejava.langpackage, available to every program, the same asStringandMath. - A start that any value beats (slide 6). Students have used
Integer.MAX_VALUEsince Topic 1.5; now they can read it as astaticconstant of theIntegerclass (Topic 3.7). Cover the table’s right columns and have students fill inshortestafter each wait before you reveal: 2147483647, 14, 6, 6, 6. The first comparison is always true, so the minimum takes a real value immediately. RunFastestLapfor a second data set. - 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. RunWarmestZeroBugto 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
- Autoboxing (4.7.A.2, slides 8–9). Show
Autobox.javaon slide 9. Ask, “Where is thenew?” There is none: when anintis assigned to anIntegervariable (Integer laps = 8;) or passed to anIntegerparameter (showLaps(12)), the compiler adds the code that builds the object. Same fordoubletoDouble(Double miles = 3.5;). Printing a wrapper shows its number, not an address: the output is8 3.5andLaps: 12. RunAutoboxParameterto show a literal and a variable both boxing at a parameter. - Unboxing (4.7.A.3, slide 10). The mirror image: an
Integerassigned to anintvariable (int copy = stored;) or passed to anintparameter (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 9and15.0. - 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 anintwidens to adouble. Reveal the error,int cannot be converted to Double, and the fix,5.0. RunBoxWrongType. Then the bottom row: unboxing then widening is fine (double x = n;prints4.0, demoUnboxWiden), but unboxing aDoubleinto anintwould narrow, so it does not compile, for the same reasonint stars = 4.0;fails. - Unboxing null (slide 12). Ask where this program fails: at compile time, or on which line at run time? Then reveal:
Checking recordprints, and the next line throws aNullPointerException. Unboxing calls a method on the object to get its number (the message namesintValue()), and calling a method throughnullthrows, just as in Topic 1.14. The compiler cannot catch it because the types are correct. RunUnboxNull.
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
intinto anIntegervariable). - Line 2: unbox (
ticketsis used in arithmetic; the result, 37, goes into anint). - Line 3: autobox (a
doubleinto aDoublevariable). - Line 4: unbox (
costis used in arithmetic;leftis anintthat widens, which is not boxing). The output is83.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
- Immutable (4.7.A.1, slides 14–15). An
IntegerorDoubleobject can never change after it is created; neither class has a method that changes the stored number. Students know the word fromStringin Topic 1.15. Show the code on slide 15 and ask for the output before revealing it. Then walk throughpoints = points + 2;step by step on the board: unbox 7, add 2, box 9 into a new object, makepointsrefer to it.savedstill refers to the old object, so the output is9then7. Settle the warm-up vote: the other variable does not see the change. RunIntegerAliasfor a second case. - A method cannot change your Integer (slide 16). Ask what
Tip.javaprints before revealing it.billgets a copy of the reference;bill = bill + 5;builds a new object and changes only the parameter (Topic 3.6), so the output isInside: 25andIn main: 20. RunIntegerParameter. Ask, “How couldmainget 25?” Collect “return it”, and writetotal = addTip(total);withaddTipreturning anInteger. That is exactly worksheet question 9’s fix, so do not show the full program. - Comparing wrapper values. Briefly, without a slide: when both sides of
==areIntegerobjects,==compares references, as with twoStringvariables in Topic 2.6, so it is not a reliable way to compare their numbers. Compare withequals, or unbox intointvariables first. RunCompareValues. 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
- 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 arestaticmethods (Topic 3.7), called through the class name, never through an object.parseIntreturns anintandparseDoublereturns adouble. - One record from a file (slide 18). Students know
splitfrom Topic 4.6. Cover the output and the table, then have students fill in the type and value ofparts[1],points, andhours. Reveal:"42"is aString,pointsis theint42,hoursis thedouble3.5. The output isLee: 43(the parentheses make+ 1add before joining) and12.0(42 / 3.5). RunParseRecordfor a second record. - 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 printsReading miles, then throws aNumberFormatException. Walk the table at the bottom of the slide:"75"works for both methods,"2.75"works only forparseDouble, and" 14"(a leading space) crashes both. The compiler cannot catch any of these, because anyStringis a legal argument. RunParseIntDecimal, thenSplitSpaceto show where a stray space comes from: splittingLee, 14on","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:parseIntgives theint12, but"3"is aString, so+joins.15: both operands areintvalues, so+adds.0.5:parseDouble("4")is 4.0, and 4.0 / 8 is adoubledivision.
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:
Double total = 0;instead ofDouble total = 0.0;— does not compile: anintcannot box into aDouble.Integer.parseInt(p)instead ofDouble.parseDouble(p)— compiles, then throws aNumberFormatExceptionon"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.