Wednesday, April 15, 2009

Java Wrapper Classes (java.lang package)

(java.lang package) Wrapper Classes in Java:

Each of Java's eight primitive data types has a class dedicated to it. These are known as wrapper classes, because they "wrap" the primitive data type into an object of that class. So, there is an Integer class that holds an int variable, there is a Double class that holds a double variable, and so on. The wrapper classes are part of the java.lang package, which is imported by default into all Java programs.

For each primitive type there is a Wrapper Class: Boolean, Byte, Character, Double, Float, Integer, Long, and Short. Byte, Double, Float, Integer and Short extend the abstract Number class and all are public final ie cannot be extended.

Classes have two constructor forms:

  • constructor that takes the primitive type and creates an object eg Character(char), Integer(int)
  • constructor that converts a String into an object eg Integer("1"). Throws a NumberFormatException if the String cannot be converted to a number.
There is also a wrapper class for Void which cannot be instantiated.

Observe that an Object starts with a capital letter, while the primitives all start with a lowercase and also remember that Strings are Ojects.

Check here for primitive to Wrapper mapping:
byte --> Byte
short --> Short
int --> Integer
long --> Long
char --> Character
float --> Float
double --> Double
boolean --> Boolean
void --> Void
Sample Code for some of the Java Wrapper Classes :
Integer:
int i = 5;
Integer I = Integer.valueOf(i); //Wrapper Class
int i2 = I.intValue(); //Converting to primitive

Float:
float f = 5.5f;
Float F = Float.valueOf(f); //Wrapper Class
float f2 = F.floatValue(); //Converting to primitive

Double:
double d = 5.55555;
Double D = Double.valueOf(d); //Wrapper Class
double d2 = D.doubleValue(); //Converting to primitive

Boolean:
boolean b = true;
Boolean B = Boolean.valueOf(b); //Wrapper Class
boolean b2 = B.booleanValue(); //Converting to primitive
The wrapper classes also provide various tools such as constants nd static methods. We will often use wrapper methods to convert a number type value to a string or a string to a number type as mentioned above.

0 comments:

Blog Widget by LinkWithin

JS-Kit Comments

  © Blogger template Newspaper III by Ourblogtemplates.com 2008

Back to TOP