Lesson 44 +10 XP

Wrapper Classes

Wrapper Classes

Wrapper classes turn primitive types into objects. They give primitives extra methods and let them be used where objects are required.

The wrappers

PrimitiveWrapper
byteByte
shortShort
intInteger
longLong
floatFloat
doubleDouble
booleanBoolean
charCharacter

Creating wrapper objects

Integer myInt = 5;
Double myDouble = 5.99;
Character myChar = 'A';

Java converts the primitive to an object automatically.

Useful wrapper methods

System.out.println(myInt.intValue());       // 5
System.out.println(myDouble.doubleValue()); // 5.99

There is also toString() to convert to a String:

String s = myInt.toString();

Why wrappers matter

  • Collections like ArrayList only store objects, so primitives need wrappers.
  • Wrappers provide useful helper methods.

TL;DR

  • Wrappers box primitives into objects.
  • int -> Integer, double -> Double, etc.
  • Needed when using collections.