The Java Library java.lang
provides eight classes in the package to represent each of the eight basic Types. These classes are called wrapper classes because they wrap the original values in the Object.
The following table lists the original types and their corresponding wrapper classes.
Basic Type |
Packing class |
Byte |
Byte |
Short |
Short |
Int |
Integer |
Long |
Long |
Float |
Float |
Double |
Double |
Char |
Character |
Boolean |
Boolean |
Method
All wrapper classes are Immutable. They provide two ways to create objects for them:
- Using constructors
- Using
valueOf()
factory methods
In addition Character
to this, each wrapper class provides at least two constructors: one with the corresponding base type and the other with the value of the String
type.
Character
The class only provides an accepted char
Constructor.
Example
The following code creates objects for some wrapper classes:
PublicClassMain{PublicStaticvoidStaticmethod(){Creates an integer object from an int intObj1=NewInteger(100);Creates an integer object from a String Integer intObj2=NewInteger("1969");Creates a double object from a double double doubleObj1=NewDouble(10.45);Creates a double object from a String double doubleObj2=NewDouble("234.60");Creates a Character object from a char Character charObj1=NewCharacter(A);Creates a Boolean object from a Boolean Boolean booleanObj1=NewBoolean(true); //creates Boolean objects from Strings boolean booleantrue = new boolean("true"); Boolean Booleanfalse = new boolean("false"); }}< /c2>
JavavalueOf ()
Another way to create wrapper class objects is to use their valueOf()
methods. valueOf()
method is a static method.
The following code uses their valueOf()
methods to create objects for some wrapper classes:
PublicClassMain{PublicStaticvoidStaticmethod(){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 '); }}< /c3>
Java
Java Data type Wrapper