Go4Expert

Go4Expert (http://www.go4expert.com/)
-   Java (http://www.go4expert.com/articles/java-tutorials/)
-   -   Wrapper Class In Java (http://www.go4expert.com/articles/wrapper-class-java-t22183/)

techgeek.in 22May2010 22:26

Wrapper Class In Java
 
Java is an object-oriented language and as said everything in java is an object. But what about the primitives? They are sort of left out in the world of objects, that is, they cannot participate in the object activities, such as being returned from a method as an object, and being added to a Collection of objects, etc. . As a solution to this problem, Java allows you to include the primitives in the family of objects by using what are called wrapper classes.

There is a wrapper class for every primitive date type in Java. This class encapsulates a single value for the primitive data type. For instance the wrapper class for int is Integer, for float is Float, and so on. Remember that the primitive name is simply the lowercase name of the wrapper except for char, which maps to Character, and int, which maps to Integer.

The wrapper classes in the Java API serve two primary purposes:
  • To provide a mechanism to “wrap” primitive values in an object so that the primitives can be included in activities reserved for objects, like as being added to Collections, or returned from a method with an object return value.
  • To provide an assortment of utility functions for primitives. Most of these functions are related to various conversions: converting primitives to and from String objects, and converting primitives and String objects to and from different bases (or radix), such as binary, octal, and hexadecimal.
The wrapper object of a wrapper class can be created in one of two ways: by instantiating the wrapper class with the new operator or by invoking a static method on the wrapper class. We will explore this further in this article.

Creating Wrapper Objects with the new Operator



Before we can instantiate a wrapper class, we need to know its name and the arguments its constructor accepts. The name of the wrapper class corresponding to each primitive data type, along with the arguments its constructor accepts, is listed below:

Primitive datatype-->Wrapper Class-->Constructor arguments
  • boolean--> Boolean--> boolean or String
  • byte--> Byte--> byte or String
  • char--> Character--> char
  • short--> Short--> short or String
  • int-->Integer--> int or String
  • long--> Long--> long or String
  • float-->Float--> float double or String
  • double-->Double--> double or String
All the wrapper classes are declared final. That means you cannot derive a subclass from any of them.All the wrapper classes except Boolean and Character are subclasses of an abstract class called Number, whereas Boolean and Character are derived directly from the Object class.All of the wrapper classes except Character provide two constructors: one that takes a primitive of the type being constructed, and one that takes a String representation of the type being constructed—for example,

Code:

Boolean wboo = new Boolean("false");
Boolean yboo=new Boolean(false);
Byte wbyte = new Byte("2");
Byte ybyte=new Byte(2);
Short wshort = new Short("4");
Short yshort = new Short(4);
Integer wint = new Integer("16");
Integer yint = new Integer(16);
Long wlong = new Long("123");
Long ylong = new Long(123);
Float wfloat = new Float("12.34f");
Float yfloat = new Float(12.34f);
Double wdouble = new Double("12.56d");
Double wdouble = new Double(12.56d);
Character c1 = new Character('c');

The value may also be passed as a variable, as shown in the following example:

Code:

boolean boo = false;
Boolean wboo = new Boolean(boo);
byte b = 2;
Byte wbyte = new Byte(b);
short s = 4;
Short wshort = new Short(s);
int i = 16;
Integer wint = new Integer(i);
long l = 123;
Long wlong = new Long(l);
float f = 12.34f;
Float wfloat = new Float(f);
double d = 12.56d;
Double wdouble = new Double(d);

Note that there is no way to modify a wrapped value—that is, the wrapped values are immutable. To wrap another value, you need to create another object.

Wrapping Primitives Using a static Method



All wrapper classes offers static valueOf() methods which give you another approach to creating wrapper objects. Because it's a static method, it can be invoked directly on the class (without instantiating it), and will return the corresponding object that is wrapping what you passed in as an argument.

Both methods take a String representation of the appropriate type of primitive as their first argument, the second method (when provided) takes an additional argument, int radix, which indicates in what base (for example binary, octal, or hexadecimal) the first argument is represented—for example,

Code:

Integer i2 = Integer.valueOf("101011", 2);  // converts 101011 to 43 and assigns the
                                          // value 43 to the Integer object i2

or

Code:

Float f2 = Float.valueOf("3.14f");  // assigns 3.14 to the Float object f2
Methods to Create Wrapper Objects

Wrapper class-->method Signature-->method arguments
  • Boolean--> static Boolean valueOf(…)-->boolean or String
  • Character--> static Character valueOf(…)-->Char
  • Byte--> static Byte valueOf(…)-->byte, String, or String and radix
  • Short--> static Short valueOf(…)-->short, String, or String and radix
  • Integer--> static Integer valueOf(…)-->int, String, or String and radix
  • Long--> static Long valueOf(…)-->long, String, or String and radix
  • Float--> static Float valueOf(…)-->float or String
  • Double--> static Double valueOf(…)-->double or String
The valueOf(…) method in the Character class accepts only char as an argument, while any other wrapper class will accept either the corresponding primitive type or String as an argument.The valueOf(…) method in the integer number wrapper classes (Byte, Short, Integer, and Long) also accepts two arguments together: a String and a radix, where radix is the base.

Using Wrapper Conversion Utilities



A storage capability without the corresponding retrieval capability is not of much use. Once you store a primitive in a wrapper object, often you will want to retrieve the stored primitive at a later time.

xxxValue() method

When you need to convert the value of a wrapped numeric to a primitive, use one of the many xxxValue() methods. All of the methods in this family are no-arg methods. Each of the six numeric wrapper classes has six methods, so that any numeric wrapper can be converted to any primitive numeric type.

Code:

Integer i2 = new Integer(42);  //  make a new wrapper object
byte b = i2.byteValue();        //  convert i2's value to a byte primitive
short s = i2.shortValue();      //  another of Integer's xxxValue methods
double d = i2.doubleValue(); //  yet another of Integer's xxxValue methods

or

Code:

Float f2 = new Float(3.14f);  // make a new wrapper object
short s = f2.shortValue();    // convert f2's value to a short primitive
System.out.println(s);        // result is 3  (truncated, not rounded)

xxx Parsexxx(String) method

If you do not need to store a value in a wrapper but just want to perform a quick operation on it, such as converting the type, you can do it by using an appropriate static method of the appropriate wrapper class. For example, all the wrapper classes except Character offer a static method that has the following signature:

static <type> parse<Type>(String s)

The <type> may be any of the primitive types except char (byte, short, int, long, float, double, or boolean), and the <Type> is the same as <type> with the first letter uppercased; for example:

static int parseInt (String s)

Each of these methods parses the string passed in as a parameter and returns the corresponding primitive type.

For example, consider the following code:

Code:

String s = "123";
int i = Integer.parseInt(s);

The second line will assign an int value of 123 to the int variable i.

Methods to Convert Strings to Primitive Types

Wrapper Class--> Method Signature--> Method Arguments
  • Boolean--> static boolean parseBoolean(…)--> String
  • Character--> Not Available
  • Byte static byte parseByte(…)--> String, or String and radix
  • Short--> static short parseShort(…)--> String, or String and radix
  • Integer--> static int parseInt(…)--> String, or String and radix
  • Long--> static long parseLong(…)--> String, or String and radix
  • Float--> static float parseFloat(…)--> String
  • Double--> static double parseDouble(…)--> double or String
parseXxx() and valueOf()

The six parseXxx() methods (one for each numeric wrapper type) are closely related to the valueOf() method that exists in all of the numeric wrapper classes (plus Boolean). Both parseXxx() and valueOf() take a String as an argument, throw a NumberFormatException if the String argument is not properly formed, and can convert String objects from different bases (radix), when the underlying primitive type is any of the four integer types.

The difference between the two methods is:
  • parseXxx() returns the named primitive.
  • valueOf() returns a newly created wrapped object of the type that invoked the method.
Some examples of these methods in action:

Code:

double d4 = Double.parseDouble("3.14");    // convert a String to a primitive
System.out.println("d4 = " + d4);              // result is  "d4 = 3.14"
Double d5 = Double.valueOf("3.14");        // create a Double object
System.out.println(d5 instanceof Double ); // result is "true"

The next examples involve using the radix argument, (in this case binary):

Code:

long L2 = Long.parseLong("101010", 2);    // binary String to a primitive
System.out.println("L2 = " + L2);        // result is "L2 = 42"
Long L3 = Long.valueOf("101010", 2);      // binary String to Long object
System.out.println("L3 value = " + L3);  // result is "L2 value = 42"

toString() method

The class Object, the super class of all classes, has a toString() method. Since we know that all other Java classes inherit from class Object, we also know that all other Java classes have a toString() method. The idea of the toString() method is to allow you to get some meaningful representation of a given object. For instance, if you have a Collection of various types of objects, you can loop through the Collection and print out some sort of meaningful representation of each object using the toString() method, which is guaranteed to be in every class. All of the wrapper classes have a no-arg, nonstatic, instance version of toString(). This method returns a String with the value of the primitive wrapped in the object—for instance,

Code:

Double d = new Double("3.14");
System.out.println("d = " + d.toString() );    //  result is "d = 3.14"

All of the numeric wrapper classes provide an overloaded, static toString() method that takes a primitive numeric of the appropriate type (Double.toString() takes a double, Long.toString() takes a long, etc.), and, of course, returns a String with that primitive’s value—for example,

Code:

System.out.println("d = " + Double.toString(3.14);    // result is "d = 3.14"
Finally, Integer and Long provide a third toString() method. It is static, its first argument is the appropriate primitive, and its second argument is a radix. The radix argument tells the method to take the first argument (which is radix 10 or base 10 by default), and convert it to the radix provided, then return the result as a String—for instance,

Code:

System.out.println("hex = " + Long.toString(254,16); // result is "hex = fe"
toXxxString() method(Binary, Hexadecimal, Octal)

The Integer and Long wrapper classes let you convert numbers in base 10 to other bases. These conversion methods, toXxxString(), take an int or long, and return a String representation of the converted number, for example,

Code:

String s3 = Integer.toHexString(254);      // convert 254 to hex
System.out.println("254 in hex = " + s3);  // result is "254 in hex = fe"
String s4 = Long.toOctalString(254);        // convert 254 to octal
System.out.println("254 in octal = "+ s4);  // result is "254 in octal = 376"


shabbir 1Jun2010 18:16

Re: Wrapper Class In Java
 
If you liked this article do nominate this article for Article of the month - May 2010

kamalesh kumar 8Aug2010 03:04

Re: Wrapper Class In Java
 
this is very helpful site for progran\ming student

cybergirl 10Dec2010 10:05

Re: Wrapper Class In Java
 
This writeup is amazing, and I want MORE. Do you have anything on Arrays?

cherylfoster 4Jan2011 00:40

Re: Wrapper Class In Java
 
A basic wrapper classes in the Java programming language is a set of 8 in the java.lang package object class provides the method provides eight primitive types. All classes in Java in the original packaging is the same. J2SE5.0 automatically boxed into their basic types of packaging an object, and automatically unpacking the packaging object to its original value of implicit conversion between object packaging and the original values.
Packaging is used to represent the original value of an object is required. Widely used packaging collections classes in the java.util package, and reflected in the java.lang.reflect package.

rameshb 4Jan2011 12:32

Re: Wrapper Class In Java
 
this is so very helpful for students thanks for the post

virender.ets 3Feb2011 17:54

Re: Wrapper Class In Java
 
Thanks for your useful content.

alexsmth114 8Mar2011 12:12

Re: Wrapper Class In Java
 
Nice informative post, couldn't have asked for more!!..

carepharmarx 17Mar2011 11:09

Re: Wrapper Class In Java
 
hi...
i am newbie here. feeling nice to take part in discussions
interesting forum
thank you for sharing

tiwvinay 14May2011 15:26

Re: Wrapper Class In Java
 
this amazing posting for wrapper java.

ankush999 15May2011 11:34

Re: Wrapper Class In Java
 
hi,
I am a student and I personally feel that this site is very useful for programming student.


regards
ankush:happy:

seemasinghal 13Jul2011 14:17

Re: Wrapper Class In Java
 
actually nice info

guptasandeep 17Dec2011 16:38

Re: Wrapper Class In Java
 
explained very effectively. good job...

Balaji Reddy 23Mar2012 16:52

Re: Wrapper Class In Java
 
A good article :)


All times are GMT +5.5. The time now is 19:28.