Unit 4 · 15 min
4.7 Wrapper Classes
Wrapper classes let a primitive value live inside an object, and the compiler boxes and unboxes for you.
Summary, objectives and course and exam description (CED) codes
Integer and Double are wrapper classes in java.lang that store an int or a double inside an immutable object. The compiler converts automatically: autoboxing turns an int into an Integer (or a double into a Double), and unboxing turns it back, when a value is passed as a parameter or assigned to a variable of the other type. Integer.parseInt and Double.parseDouble turn a String such as "42" into a number.
By the end of this session you can
- 4.7.A Develop code to use Integer and Double objects from their primitive counterparts and determine the result of using these objects.
Reviewed against the CED on
1LearnThe notes, the traps and how to remember them
1. Integer and Double objects
Each primitive type has a matching wrapper class whose objects hold one value of that type. For the AP® exam you need two: Integer (wraps an int) and Double (wraps a double). Both are part of the java.lang package 4.7.A.1, like String and Math, so no import is needed.
Integer objects are immutable: once an Integer object is created, its attributes cannot be changed 4.7.A.1. Double objects are immutable in the same way 4.7.A.1. There is no method like setValue.
| Primitive type | Wrapper class | Example value |
|---|---|---|
int |
Integer |
42 |
double |
Double |
3.75 |
Why bother? Some Java code only works with objects. The most important example is ArrayList (topic 4.8), which stores object references. A list of whole numbers must use Integer:
ArrayList<int> laps = new ArrayList<int>();
Compiler error:
error: unexpected type
2. Autoboxing
Autoboxing is the automatic conversion the Java compiler makes from a primitive type to its wrapper class: an int to an Integer, a double to a Double 4.7.A.2. The compiler applies it when a primitive value is assigned to a variable of the wrapper class, or passed as a parameter to a method that expects an object of that wrapper class 4.7.A.2.
public static void showBoxed(Integer box)
{
System.out.println("Received the object " + box);
}
Integer goals = 3; // assigned to an Integer variable: autoboxing
Double price = 4.99; // assigned to a Double variable: autoboxing
int bonus = 7;
showBoxed(bonus); // passed to an Integer parameter: autoboxing
System.out.println(goals + " " + price);
Output:
Received the object 7
3 4.99
The match must be exact in type: a double value cannot be boxed into an Integer.
Integer wrong = 4.5;
Compiler error:
error: incompatible types: double cannot be converted to Integer
3. Unboxing
Unboxing is the automatic conversion the Java compiler makes from a wrapper class to its primitive type: an Integer to an int, a Double to a double 4.7.A.3. The compiler applies it when a wrapper object is assigned to a variable of the primitive type, or passed as a parameter to a method that expects that primitive type 4.7.A.3.
public static double half(double value)
{
return value / 2;
}
Integer stored = 25;
Double rate = 0.5;
int plain = stored; // assigned to an int variable: unboxing
System.out.println(plain + 5);
System.out.println(half(rate)); // passed to a double parameter: unboxing
System.out.println(stored * rate); // arithmetic unboxes both
Output:
30
0.25
12.5
Watch out: a wrapper variable is a reference, so it can be null. Unboxing null fails at run time.
Integer missing = null;
int value = missing;
System.out.println(value);
Output:
Exception in thread "main" java.lang.NullPointerException: Cannot invoke "java.lang.Integer.intValue()" because "missing" is null
The program stops with a NullPointerException. (The exact wording after the colon depends on your Java version and settings; on the AP® exam you only need the exception name.)
4. Immutable in practice
Because Integer objects cannot change, code that looks like it changes one actually creates a new object. The variable gets a reference to the new object, and any other variable still refers to the old one.
Integer score = 10;
Integer saved = score; // both refer to the same Integer object
score++; // unbox 10, add 1, box 11 into a NEW object
System.out.println(score);
System.out.println(saved);
Output:
11
10
Watch out: == on two wrapper objects compares references, not values. Compare with equals, or unbox to int first.
Integer a = 1000;
Integer b = 1000;
int x = a; // unboxing
int y = b; // unboxing
System.out.println(a.equals(b));
System.out.println(x == y);
System.out.println(a == b);
Output:
true
true
false
(The == result for small values such as 5 can be true, because Java reuses some small Integer objects. Never rely on it.)
5. parseInt and parseDouble
Data read from a file or split from a line arrives as String values. Two static methods in the Java Quick Reference convert them to numbers:
static int parseInt(String s)inIntegerreturns theStringargument as anint4.7.A.4.static double parseDouble(String s)inDoublereturns theStringargument as adouble4.7.A.5.
String line = "Ana,12,8.5";
String[] parts = line.split(",");
int points = Integer.parseInt(parts[1]);
double minutes = Double.parseDouble(parts[2]);
System.out.println(parts[1] + parts[1]); // String + String: joins
System.out.println(points + points); // int + int: adds
System.out.println(points / minutes);
Output:
1212
24
1.411764705882353
Watch out: the String must really look like a number of that type, or the program stops with a NumberFormatException.
System.out.println(Double.parseDouble("12"));
System.out.println(Integer.parseInt("12.0"));
Output:
12.0
Exception in thread "main" java.lang.NumberFormatException: For input string: "12.0"
parseDouble("12") works (a whole number is a valid double), but parseInt("12.0") fails.
Lock it in: memory hooks
- AutoboxingBox it up: a primitive goes into a box (object) automatically.
- UnboxingUnpack it: the value comes out of the box when a primitive is needed.
- ParsingparseInt reads digits from text: "42" becomes 42.
Common misconceptions
"Integer and int are the same thing."
Not quite. int is a primitive type that holds a value. Integer is a class; an Integer variable holds a reference to an object (or null). Autoboxing and unboxing just make it easy to move between them.
"count++ on an Integer changes the object."
Not quite. Integer objects are immutable. count++ unboxes the value, adds 1, and boxes the result into a different Integer object. Other variables that referred to the old object still see the old value.
"Integer.parseInt("3.5") returns 3."
Not quite. parseInt needs a String that looks like an int. "3.5" throws a NumberFormatException. Use Double.parseDouble for decimals.
"Unboxing always works."
Not quite. An Integer variable can be null. Unboxing null (for example int x = maybe;) throws a NullPointerException.
Exam traps
- parseInt and parseDouble are static: call them on the class, Integer.parseInt(s), not on a String.
- Integer.parseInt("12.0") and Integer.parseInt("twelve") throw a NumberFormatException at run time.
- Use equals or compare unboxed int values; == on two Integer objects compares references.
- Integer x = 4.5; does not compile: a double cannot be boxed into an Integer.
2PracticeRecall it, then check yourself
In 30 seconds
- Integer and Double are in java.lang (no import) and are immutable: once created, their attributes cannot change.
- Autoboxing: int to Integer or double to Double, when passed to a parameter or assigned to a variable of the wrapper type.
- Unboxing: Integer to int or Double to double, when passed to a parameter or assigned to a variable of the primitive type.
- Integer.parseInt(s) returns the String s as an int; Double.parseDouble(s) returns it as a double.
- Wrapper variables can be null; unboxing null throws a NullPointerException.
Cover this list, say the points out loud, then take the checkpoint without scrolling back up.
Checkpoint · 5 questions
Checkpoint: Wrapper Classes
Pick an answer to mark it. Every answer is explained, and you can try any question again. Your saved score counts first tries only, and stays in this browser.
3PrevailLock it in for exam day
By the numbers
- When the compiler applies autoboxing to a primitive value two situations CED 4.7.A.2
- it is passed as a parameter to a method that expects the matching wrapper class
- it is assigned to a variable of the matching wrapper class
- When the compiler applies unboxing to a wrapper object two situations CED 4.7.A.3
- it is passed as a parameter to a method that expects the matching primitive type
- it is assigned to a variable of the matching primitive type
- Wrapper class methods in the Java Quick Reference for this topic two methods CED 4.7.A.4, 4.7.A.5
Key terms: flip the cards
Read the term, say the definition out loud, then flip to check. Struggling a little to remember is what makes it stick.
-
Wrapper classtap to flip
A class whose objects hold one primitive value; for the AP® exam, Integer wraps an int and Double wraps a double.
Example and CED codes -
Integer (class)tap to flip
The java.lang wrapper class whose immutable objects hold one int value; Integer.parseInt(s) returns a String as an int.
Example and CED codes -
Double (class)tap to flip
The java.lang wrapper class whose immutable objects hold one double value; Double.parseDouble(s) returns a String as a double.
Example and CED codes -
Autoboxingtap to flip
The automatic conversion the compiler makes from a primitive value to its wrapper class object, such as int to Integer or double to Double.
Example and CED codes -
Unboxingtap to flip
The automatic conversion the compiler makes from a wrapper class object to its primitive value, such as Integer to int or Double to double.
Example and CED codes -
Primitive typetap to flip
A data type for numbers and Boolean values whose variables hold the value directly. In this course: int, double and boolean.
Example and CED codes -
Reference typetap to flip
A data type used to define objects, that is, anything that is not a primitive type. Every class defines a reference type.
Example and CED codes
Questions students ask
What is a wrapper class in Java?
A class whose objects hold one primitive value. For AP® Computer Science A, Integer wraps an int and Double wraps a double.
What is the difference between autoboxing and unboxing?
Autoboxing converts a primitive to its wrapper object (int to Integer). Unboxing converts a wrapper object back to its primitive (Integer to int). The compiler does both automatically.
Why do we need Integer if we have int?
Some code only works with objects. An ArrayList, for example, stores object references, so a list of whole numbers is an ArrayList<Integer>, not an ArrayList<int>.
How do I convert a String to an int in Java?
Use Integer.parseInt, for example int n = Integer.parseInt("250");. For decimals use Double.parseDouble.