Wrapper classes offer a means to utilize primitive data types (such as int, boolean, etc.) as objects.
The table below lists the primitive types alongside their corresponding wrapper classes:
Primitive Data Type |
Wrapper Class |
Byte |
Byte |
short |
Short |
int |
Integer |
long |
Long |
float |
Float |
double |
Double |
boolean |
Boolean |
char |
Character |
At times, wrapper classes are necessary, particularly when dealing with Collection objects like ArrayList, where primitive types cannot be employed directly, as the list can only accommodate objects.
ArrayList<int> myNumbers = new ArrayList<int>(); // Invalid |
ArrayList<Integer> |
To instantiate a wrapper object, utilize the wrapper class instead of the primitive type. Retrieving the value can be achieved by simply printing the object.
public |
Now that you’re working with objects, you can employ specific methods to obtain information about the particular object.
For instance, you can utilize the following methods to retrieve the value associated with the respective wrapper object: intValue(), byteValue(), shortValue(), longValue(), floatValue(), doubleValue(), charValue(), and booleanValue().
This example will yield identical results to the one provided above:
public |
Another valuable method is toString(), employed to convert wrapper objects into strings.
In the subsequent example, we convert an Integer to a String, then utilize the length() method of the String class to display the length of the resulting string.
public |