· Wrapper classes can be used to convert primitive data types like int, float, long, and double to objects.
· These classes are contained in the java.lang package.
· The classes Byte, Double, Float, Integer and Short extend the abstract Number class
· All the wrapper classes are public final ie cannot be extended
· In addition to conversion methods, they also have some additional methods. (eg. Character.isDigit())
· All the wrapper classes have two constructor forms
ü A constructor that takes the primitive type and creates an object eg Character(char), Integer(int)
ü A constructor that converts a String into an object eg Integer("1"). But, this type of constructor is not available with Character class.
· The methods of the wrapper classes are all static so you can use them without creating an instance of the matching wrapper class.
· Once assigned a value, the value of a wrapper class cannot be changed
· The wrapper classes are just that classes, they are not primitives and instances of the wrappers can only be manipulated in the same way as any class.
The following table lists simple data types and their corresponding wrapper classes.
Simple Type | Wrapper class |
boolean | Boolean |
char | Character |
double | Double |
float | Float |
int | Int |
long | Long |
byte | Byte |
short | Short |
To convert primitive data types to objects, we write
Integer iObj = new Integer(30);
Float fObj = new Float(3.4);
Double dObj = new Double(9.8);
To convert objects to primitive data types, we write
int x = iObj.intValue( );
float f = fObj.floatValue( );
double d = dObj.doubleValue( );
To convert String objects to Wrapper-class objects, we write
iObj = Integer.valueOf(“30”);
fObj = Float.valueOf(“3.4”);
dObj = Double.valueOf(“8.99”);
0 comments:
Post a Comment