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.

4.7.A4.7.A.14.7.A.24.7.A.34.7.A.44.7.A.5

Reviewed against the CED on

Know this already? Jump to the checkpoint.

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) in Integer returns the String argument as an int 4.7.A.4.
  • static double parseDouble(String s) in Double returns the String argument as a double 4.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

  1. Integer and Double are in java.lang (no import) and are immutable: once created, their attributes cannot change.
  2. Autoboxing: int to Integer or double to Double, when passed to a parameter or assigned to a variable of the wrapper type.
  3. Unboxing: Integer to int or Double to double, when passed to a parameter or assigned to a variable of the primitive type.
  4. Integer.parseInt(s) returns the String s as an int; Double.parseDouble(s) returns it as a double.
  5. 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.

  1. 1 Consider the following code segment. What is printed as a result of executing the code segment? 4.7.A.1, 4.7.A.2, 4.7.A.3
    Integer a = 7;
    Integer b = a;
    a = a + 3;
    System.out.println(a + " " + b);
    Show answer

    Answer: B. Integer objects are immutable. a + 3 unboxes 7, adds 3 and boxes 10 into a new object, which a now refers to; b still refers to the old object holding 7. "10 10" assumes the shared object was changed, "7 7" ignores the assignment, and "7 10" swaps the variables.

  2. 2 Consider the following code segment. What is printed as a result of executing the code segment? 4.7.A.4, 4.7.A.5
    String s = "4";
    String t = "2.5";
    System.out.println(s + Integer.parseInt(s) + Double.parseDouble(t));
    Show answer

    Answer: C. The expression is evaluated left to right: "4" + 4 is the String "44", and "44" + 2.5 is "442.5". "10.5" would need the numbers added first, "6.5" adds only the two parsed values, and "44 2.5" adds a space that is not in the code.

  3. 3 In which of the following statements does autoboxing occur? 4.7.A.2
    Show answer

    Answer: D. Autoboxing happens when a primitive value is assigned to a variable of the matching wrapper class: the double 3.5 becomes a Double object. parseInt returns an int stored in an int (no object), double y = 3 is a widening conversion between primitives, and (int) 3.5 is a cast between primitives.

  4. 4 Consider the following code segment. What is the result of executing the code segment? 4.7.A.3
    Integer best = null;
    int score = 8;
    if (score > 10)
    {
        best = score;
    }
    int result = best + 1;
    System.out.println(result);
    Show answer

    Answer: A. Because score > 10 is false, best stays null. best + 1 needs to unbox best, and unboxing null throws a NullPointerException at run time. A null Integer is not treated as 0, so "1" is wrong; 9 would need best to hold 8; and the compiler cannot know the value is null, so the code compiles.

  5. 5 Consider the following code segment. What is printed as a result of executing the code segment? 4.7.A.4
    String[] parts = "7,3.5".split(",");
    int a = Integer.parseInt(parts[0]);
    double b = Double.parseDouble(parts[1]);
    System.out.println(a + b);
    Show answer

    Answer: D. parts is {"7", "3.5"}. Integer.parseInt("7") returns the int 7 and Double.parseDouble("3.5") returns the double 3.5, so a + b is numeric addition: 10.5. "10" and "10.0" drop the .5 as if 3.5 were read as an int, and "73.5" joins the two String parts instead of adding the parsed numbers.

3PrevailLock it in for exam day

By the numbers

Name each list from memory, then reveal it to check. Each list shows how many items to recall.

  • When the compiler applies autoboxing to a primitive value two situations CED 4.7.A.2
    1. it is passed as a parameter to a method that expects the matching wrapper class
    2. 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
    1. it is passed as a parameter to a method that expects the matching primitive type
    2. 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
    1. static int parseInt(String s) in Integer
    2. static double parseDouble(String s) in Double

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
  • Objecttap to flip

    A specific instance of a class with defined attributes.

    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.

Was this page helpful?

No names are ever shown, and every public comment is checked by us first. Please do not include personal details. To get a reply, email [email protected].

↑ Top

Enlarged view of the selected figure