When working with
Collection objects, such as ArrayList, we use Wrapper Classes (the primitive
types cannot be used). The List can only use objects.
Example
ArrayList<int> numbers = new ArrayList<int>(); // Invalid
ArrayList<Integer> numbers = new ArrayList<Integer>(); // Valid
Creating Wrapper Objects
To create a wrapper
object, use the wrapper class instead of primitive type. To get the value of
the object, we just print the object.
Example
public class WrapperObject {
public static void main (String args[]){
Integer myInt = 100;
Double myDouble = 9.999;
Character myChar = 'R';
System.out.println(myInt);
System.out.println(myDouble);
System.out.println(myChar);
}
}
Output
100
9.999
R
As we are now working with
objects, we can use certain methods to get information about the specific object
such as intValue(), charValue(), byteValue(), shortValue(), longValue(), floatValue(), doubleValue() and booleanValue() are
associated with their corresponding wrapper classes.
The above example will output the same
result as the example below:
Example
public class WrapperObject {
public static void main (String args[]){
Integer myInt = 100;
Double myDouble = 9.999;
Character myChar = 'R';
System.out.println(myInt.intValue());
System.out.println(myDouble.doubleValue());
System.out.println(myChar.charValue());
}
}
Output
100
9.999
R
Convert
Wrapper Objects to Strings
We can convert wrapper objects to
Strings using toString() method.
Example
In the below example, we convert an Integer
to
a String and we use the length() method of the String class to output the length of the String:
public class WrapperObject {
public static void main (String args[]){
Integer myInt = 10000;
String myString = myInt.toString(); //Convert Integer to String
System.out.println(myString.length()); //Length of the String
}
}
Output
5