ACSA Exam Prep
Unit 4 · Data Collections · Topic 4.7

Wrapper Classes

Skill 2.B

Big idea: Integer and Double wrap a primitive inside an object so it can go where only objects are allowed, such as an ArrayList. Java converts back and forth for you.

Learning objectives
  • Develop code to use Integer and Double objects from their primitive counterparts and determine the result of using these objects.

Autoboxing and unboxing

Autoboxing: Java turns an int into an Integer (or a double into a Double) when an object is needed. Unboxing is the reverse.

Code
Integer boxed = 42;          // autobox
int plain = boxed + 8;       // unbox, then add
ArrayList<Integer> list = new ArrayList<Integer>();
list.add(7);                 // autobox 7
int first = list.get(0);     // unbox
System.out.println(plain + " " + first);
Output
50 7

Parsing strings

Text from a file or split comes in as Strings. Convert with the static parse methods.

Code
int n = Integer.parseInt("125");
double d = Double.parseDouble("2.5");
System.out.println(n + 1);
System.out.println(d * 2);
System.out.println("125" + 1);
System.out.println(Integer.MAX_VALUE);
Output
126
5.0
1251
2147483647
Key points
  • Integer and Double are in java.lang and are immutable.
  • Autoboxing: primitive → wrapper automatically. Unboxing: wrapper → primitive.
  • Integer.parseInt(s) and Double.parseDouble(s) convert Strings to numbers.
  • Integer.MIN_VALUE and Integer.MAX_VALUE are the int limits.
Watch out
  • ArrayList can't hold primitives: write ArrayList<Integer>, not ArrayList<int>.
Quick check
What is Integer.parseInt("40") + Integer.parseInt("2")?
Show answer
42 (int addition, not concatenation).