Monday, January 3, 2011

Wrapper Class In Java

The Java sample program below use the Wrapper Class, it will serve as an example program to those who want to learn on how to program in Java, and to familiarize on how to use the Java Wrapper Class.  Obviously, the primitive data types such as int, char and long are not objects. Thus, variables of these data types cannot access methods of the Object class. Only actual objects, which are declared to be of reference data type, can access methods of the Object class. There are cases, however, when you need an object representation for the primitive type variables in order to use Java built-in methods. For example, you may want to add primitive type variables to a Collection object. This is where the wrapper classes comes in. Wrapper classes are simply object representations of simple non-object variables. Here's the list of the wrapper classes.

Primitive Data Type Corresponding Wrapper Class

Boolean                            Boolean
Char                                 Character
byte                                  Byte
short                                Short
int                                    Integer
long                                  Long
float                                 Float
double                              Double

The names of the different wrapper classes are quite easy to remember since they are very similar to the primitive data types. Also, note that the wrapper classes are just capitalized and spelled out versions of the primitive data types.

Here's an example of using the wrapper class for boolean.

class BooleanWrapper {
public static void main(String args[]) {
boolean booleanVar = 1>2;
Boolean booleanObj = new Boolean("TRue");
/* primitive to object; can also use valueOf method */
Boolean booleanObj2 = new Boolean(booleanVar);
System.out.println("booleanVar = " + booleanVar);
System.out.println("booleanObj = " + booleanObj);
System.out.println("booleanObj2 = " + booleanObj2);
System.out.println("compare 2 wrapper objects: " +
booleanObj.equals(booleanObj2));
/* object to primitive */
booleanVar = booleanObj.booleanValue();
System.out.println("booleanVar = " + booleanVar);
}
}

The sample code gives the following output:

booleanVar = false
booleanObj = true
booleanObj2 = false
compare 2 wrapper objects: false
booleanVar = true

No comments:

Post a Comment