The Java library provided eight classes in the java.lang package to represent each of the eight primitive types.
These classes are called wrapper classes as they wrap a primitive value in an object.
The following table lists the primitive types and their corresponding wrapper classes.
Primitive Type | Wrapper Class |
---|---|
byte | Byte |
short | Short |
int | Integer |
long | Long |
float | Float |
double | Double |
char | Character |
boolean | Boolean |
All wrapper classes are immutable. They provide two ways to create their objects:
Each wrapper class, except Character, provides at least two constructors: one takes a value of the corresponding primitive type and another takes a String.
The Character class provides only one constructor that takes a char.
The following code creates objects of some wrapper classes:
public class Main { public static void staticMethod() { // Creates an Integer object from an int Integer intObj1 = new Integer(100); // Creates an Integer object from a String Integer intObj2 = new Integer("1969"); // Creates a Double object from a double Double doubleObj1 = new Double(10.45); // Creates a Double object from a String Double doubleObj2 = new Double("234.60"); // Creates a Character object from a char Character charObj1 = new Character('A'); // Creates a Boolean object from a boolean Boolean booleanObj1 = new Boolean(true); // Creates Boolean objects from Strings Boolean booleanTrue = new Boolean("true"); Boolean booleanFalse = new Boolean("false"); } }
Another way to create objects of wrapper classes is to use their valueOf() methods.
The valueOf() methods are static.
The following code creates objects of some wrapper classes using their valueOf() methods:
public class Main { public static void staticMethod() { Integer intObj1 = Integer.valueOf(100); Integer intObj2 = Integer.valueOf("2014"); Double doubleObj1 = Double.valueOf(10.45); Double doubleObj2 = Double.valueOf("234.56"); Character charObj1 = Character.valueOf('A'); } }