Loading lessons...
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
| Primitive | Wrapper |
|---|---|
byte | Byte |
short | Short |
int | Integer |
long | Long |
float | Float |
double | Double |
boolean | Boolean |
char | Character |
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.