Wrapper Class and Type Casting

Wrapper Class
  • Used to convert primitive values into object type and vice-versa.
  • And most of the utilities classes like ArrayList, HashMap work only on objects , not work with primitive type, but know Jdk1.5 introduce auto boxing so its not needed to convert primitive type to reference type for utilities class.
Note : Wrapper classes are immutable.

Example:
int a=100;
Integer i=new Integer(a);
int b=i.intValue();
Example:
float a=100.10f;
Float r=new Float (a);
float c=r.floatValue();
Using Wrapper Methods
Methods Descriptions Example
xxxValue()
Convert Reference Type into Primitive type. and it is not static method. Example1:
Integer i=new Integer(42);
int b=i.intValue();
Example2:
byte c=i.byteValue();
float d=i.floatValue();
parseXXX()
  • Takes String as an argument and convert it into primitive type
  • Static Method
  • NumberFormatException throws if argument is improper.
Example1:
int a=Integer.parseInt("100");
Example2
double d=Double.parseDouble("90.10");
toxxxString()
(Binary, Hexadecimal, Octal) Example1:

String s=Integer.toHexString(254);
String a=Long.toOctalString(254);
String b=Integer.toBinaryString(254);