Nov 30, 2014

Wrapper Classes



Java wrapper classes serve following primary purposes:
  • Provide a way to "wrap" primitive values in an object so that the primitive types can also be used in activities reserved for objects, like being added to Collections. Note: With Java 5's addition of auto-boxing (and unboxing), many of the wrapping operations are now handled automatically that needed to be done manually.
  • Provide utility functions for primitives, like conversion functions (converting primitives to and from String objects, and converting primitives and String objects to and from different bases, such as binary, octal, and hexadecimal).
Below table defined the Wrapper classes for primitive types with their constructors:



Primitive
Wrapper Class
Constructor Arguments
boolean
Boolean
boolean or String
byte
Byte
byte or String
double
Double
double or String
float
Float
float, double, or String
int
Integer
int or String
long
Long
long or String
short
Short
short or String

Any constructor that accepts String as an argument throws NumberFormatException.

Example:
Integer
       Integer int1 = new Integer(11);
       Integer int2 = new Integer("11");

Float
       Float float1 = new Float(1.45f);
       Float float2 = new Float("1.45f");

Character
Accepts only char as constructor argument.
       Character c1 = new Character('j');

Boolean
The constructors for the Boolean wrapper take either a boolean (true or false), or a String. For a String, “true” (case insensitive) will be considered as true, everything else will result in false. Java 5 onwards, Boolean can also be used in conditional statements.
       Boolean b1 = new Boolean(true);
       Boolean b2 = new Boolean("true");
       if (b1) // works only Java 5 onwards

Java 5 has also added new feature of auto-boxing. You can read full article here.

0 comments:

Post a Comment