Questions
What is the Wrapper class? When would I use the Wrapper class?
Answer
The Wrapper Class is initially a little confusing, but really not a complicated thing. We have not covered it, yet, since we don’t need it until we use ArrayLists. School closed before we could cover it fully. You may have actually seen them and thought them just an odd typing instead any special code. Here is the tutorial link from Edhesive about the Wrapper Class.
In Java you have two main types of variables: primitives and Objects. Primitive variables are the variables declared as int, float, double, Boolean, char, etc. They are handled in Java by assigning the variable to a simple value. Objects are more complicated and handled differently in Java but can be used to do more advanced things.
The Wrapper Class is a way to create a primitive variable as an Object. It serves the same purpose as a primitive variable, storing a single value, but it has access to Object tools. The Wrapper classes for the primitive variables are often just capitalized versions of the primitive variable:
Primitive | Wrapper |
int | Integer |
long | Long |
float | Float |
double | Double |
boolean | Boolean |
char | Character |
The only time we would normally see them is when you want to use an ArrayList or more advanced object collections. An ArrayList can only be a list of Objects. It cannot be a list of primitive variable. Arrays, though, can be either primitive variables or Objects.
Example
If I wanted to create an ArrayList of integers I would have to use the following code:
ArrayList <Integer> myIntList = new ArrayList <Integer>;
The following code would trigger an error:
ArrayList <int> myIntList = new ArrayList <int>;
Otherwise, you can use the two types interchangeably. For example:
Integer x = 10;
int y = x;
System.out.println(x);
System.out.println(y);
Both variables will be equal to 10 and will produce the same output when printed. One difference, though, is that when “x” is printed, it calls the built-in “toString” method for the Integer object in order to print it while printing “y” just prints the value.
Other Resources
Lesson 12: Wrapper classes