wrapper classes

Wrapper Classes


  • Wrapper classes are introduced in “jdk 1.4”,From “jdk1.5” onwards java supports 100% oops concepts.

  • In order to convert “primitive datatype” to” derived datatype” and “derived datatype” to “primitive datatype” we use wrapper classes

  • For every primitive datatype there is a corresponding derived datatype.

  • Primitive Datatype Derived Datatype
    byte ---------------> Byte
    short ---------------> Short
    int ---------------> Integer
    long ---------------> Long
    float ---------------> Float
    double ---------------> Double
    boolean ---------------> Boolean
    char ---------------> Character

  • For creating object ,inside every wrapper classes have 2 constructors namely.
    1.  Same type constructor
    2.  String type constructor

    javapadho
    Wrapper Class Constructor using two ways

  • Convert from primitive datatype to derived datatype:

  • This can be achieved in two different ways.
    1.  Through “new” operator.
    2.  Through “ valueOf( )”.

  • 1. Through” valueOf()” method:


       Byte b = new Byte(20); --------->Passing any primitive value
       Byte b1 = new Byte(“20”); --------->passing any string type value

    2. Through “new” operator:


       Byte b = new Byte(20); 
       Byte b1 = new Byte(“20”); 
       Integer i = Integer.valueOf(10);

    Convert from derived datatype to primitive datatype:


    • Inside every wrapper class there are 6 methods like
        

      Note
       Here XXX means byte, short, int, long, float, double.
      Example

           // Derived data type:
            Short s=new Short(50);
           // primitive data type:
           short s1=s.shortValue( )

          Note
          • If we want to convert into short primitive data type we use short in place of XXX. Like wise use xxx value for which derived data type converts into primitive datatype.

    Convert from derived datatype to primitive datatype:

    • If we want to convert one derived type to another primitive and different derived type to different primitive we should use the following way.
      Integer i=new Integer(200);

    • The above code converts primitive type int value i.e., 200 into derived type integer value as object formate.
      short s=i.shortValue( );

    • In the above line ‘s’ is short primitive type reference variable and ‘i’ is reference variable to Integer derived type. Here integer derived type ‘i’ converts into short primitive type through shortValue( ) method. Below shows some examples

      EXAMPLE :

        byte b=i.byteValue( );
        int i=i.intValue( );
        float f=i.floatValue( );
        long l=i.longValue( );
        double d=i.doubleValue( );

    • In this we have six methods one method is same type i.e., int and remaining five has different types i.e., byte, short, float, long, double.

    Convert from String to Derived Type:

    • String should contain only numeric values i.e., (0,1,2,….,9 ) else we will get java.lang.NumberFormatException.

    • Example 1:

       
                      
                   package com.sdj;
                   public class WrapperDemo 
                   {
                      public static void main(String[] args)
                      {
                         String str="123";
                         Integer i=new Integer(str);
                         Float f=new Float(str);
                         Long l=new Long(str);
                         Double d=new Double(str);
                         System.out.println("The given str is:"+str);
                         String str1 = "abc";
                         
                         /*  Integer i1 = new Integer(str1);  */
                         /*  Float f1 = new Float(str1);  */
                         /*  Long l1 = new Long(str1);  */
                         /*  Double d1 = new Double(str1);  */
                         /*  The above four lines are compile success but fails at */
                         /*  run time i,e.,    java.lang.NumberFormatException because  */
                         /*  we can’t convert alphabets  into wrapper type(Integer,Float,Byte,……..). */
                         System.out.println("The given str is:"+str1);
                      }
                   }                

         Output:

         The given str is:123
         o
         
         
         

    Convert String to Primitive:

    • Inside every wrapper class there is one method called parseXXX( ) except Character wrapper class. It will converts the String numric value to corresponding primitive equalent value. Example if you want to convert the following String “123” value to int type then we should use code like bellow
      Int intVal = Integer.parseInt(“123”);
       in parseXXX() method “XXX” means it specifies corresponding primitive type like int,float,double etc.. example
        Float.parseFloat(“12.34”);
        Double.parseDouble(“30.56”) etc….

    • Here input String value for parseXXX() should be numeric else we will get java.lang.NumberFormatException same as above.

    Example 2:

     
                    
                 package com.sdj;
                 public class WrapperStringDemo 
                 {
                    public static void main(String[] args) 
                    {
                       String str="456";
                       int i=Integer.parseInt(str);
                       float f=Float.parseFloat(str);
                       long l=Long.parseLong(str);
                       double d=Double.parseDouble(str);
                       System.out.println("The given String is:"+str);
                       System.out.println("The integer value is:"+i);
                       System.out.println("The long value is:"+l);
                       long l1 = Integer.parseLong(str);
                       double d1 = double.parseDouble(str);
                       /*  The above two lines fail at  compilation because o  */
                       /*  1.we can’t use Integer with long type. here it is undefined type */
                       /*  we can’t convert  this format. we should use same type I.e.Long  */
                       /*  otherwise it will fail.  */
                       
                       /*  2.we are tying to access primitive type double with parseDouble( str)  */
                       /*  method.it is undefined. */
                       String str1 = "abc";
                       /*  float ft = Float.parseFloat(str1);  */
                       /*  long lg = Long.parseLong(str1);  */
                       /*  Here in the above two lines compilation success but  fails at run time  */
                       /*  i.e., NumberFormatException  */
                       System.out.println("The float value is:"+ft);
                    }
                 }                

    How to convert from Derived Type to String:

    • Inside every wrapper class there is one method called toString( ) method. It defines the object format and it is inherited from the object class.

    • Example 3:

       
                      
                   class Double
                   {
                      Double d1=new Double(20.65);
                      /*  Derived type wrapper class  */
                      String s1=d1.toString( );
                      /*  Here we trying to convert ‘ d1’ derived type to String  */
                      /*  type by using toString( ) method.  */
                   }                
    • According to object class definition toString( ) method, output will be objectClassname@Hexa decimal representation of object memory location. Hexa Decimal representation means combination of numeric’s and alphabets i.e.,(123abc32def754)

    •    Excepted Output:

      javapadho
      trying to convert ‘ d1’ derived type to String

      Example 4:

       
                      
                   package com.sdj;
                   class A
                   {
                      A()
                      {
                         System.out.println("Conversion of derived to String");
                      }
                   }
                   public class Manager
                   {
                      public static void main(String[] args) 
                      {
                         Integer i = new Integer(20);
                         A a1 = new A();
                         System.out.println("The derived type Integer:::"+i);
                         System.out.println("conversion of derived to string:::"+i.toString());
                         System.out.println(a1);
                         System.out.println(a1.toString());
                         String s1 = i.toString();
                         String s2 = a1.toString();
                         System.out.println("s1 value is ::: "+s1);
                         System.out.println("s2 value is ::: "+s2);
                         /*  String s3 = a1;  */
                         /*  String s4 = i  */      
                      }
                   }                

      Output:

      Conversion of derived to String The derived type Integer:::20 conversion of derived to string:::20 com.sdj .A@82ba41 com.sdj .A@82ba41 s1 value is :::20 s2 value is :::com.sdj .@82ba41

      Explanation:

      • If we pass any derived object to the sop ,then it invokes toString( ) method automatically from that corresponding class and the result of the toString( ) will be printed into the console.

      • From the above program line no. 11&13 are equivalent to the line no 12&14 correspondingly .After compilation line no. 11&13 also convert equivalent to line no 12&14 but here from line no 11&12 we will get the o/p as state of the wrapper class object but from line no. 13&14 we will get o/p like ClassName@hexa decimal representation of memory location

      • Why because in all wrapper classes, toString( ) method get ovverided so it works based on the state of the object but in class A we are not overrided toString( ) so it works according to object class toString( ) method

      • In line no. 19&20 compilation fails because in line 19 we can’t assign class A object to String because while assignment toString( ) method won’t invoke.

      • Line 20 is also same as line no 19 here we are assigning integer object to string type i.e.,String s4=i. we should assign same and not other type.

    How to convert from Derived Type to String:

    • In order to convert derived to base types i.e., (binary, octal,hexadecimal) we should go in the following way.
      Example :
          Integer i=new Integer(20);
      To Binary :
          String s1=i.toBinaryString(20);
      To Octal :
          String s1=i.toOctalString(20);
      To Hexa Decimal :
          String s1=i.toHexaDecimalString(20);

    • We should pass Integer, Long, Float, Double wrapper type only inside base conversions but not Byte, Short, Boolean methods.
      Example :
          String s=Integer. toBinaryString(20);
          String s1=Float. toOctalString(20.124f);
          String s2=Double. toHexaDecimalString(20.65);

    • We should not pass like below methods as they are not valid.
      Example :
          String s=Byte.toBinaryString(bytevalue);
          String s=Short.toOctalString(shortvalue);


      WRAPPER CLASS HIERARCHY

      javapadho
      Wrapper Class Hierarchy
      javapadho
      Wrapper Class Flow

    Example 5:

     
                    
                 class Abc
                 {
                    int test(Object h)
                    {
                       System.out.println("Object class");
                       return 10;
                    }
                    boolean test(Long y)
                    {
                       System.out.println("Long class");
                       return true;
                    }
                    int test(Byte u)
                    {
                       System.out.println("Byte wrapper class");
                       return 60;
                    }
                 }
                 class Wraper 
                 {
                    public static void main(String[] args) 
                    {
                       System.out.println("Hello World!");
                       Integer i=new Integer(58);
                       Abc guys=new Abc();
                       System.out.println(guys.test(i));
                       Long hello=new Long("56");
                       System.out.println(guys.test(hello));
                    }
                 }                

    Output:

    Hello World! Object class. 10 Long class. True.

    Explanation:

    • In the above program , System.out.println(guys.test(i)); is a calling statement for the test() method with Integer wrapper type inside “class Abc”.So first jre will look for test method with Integer type only.

    • But there is no test() with Integer type inside “class Abc”, Then JRE will look for super type of Integer i.e (Number class or Object class) .InSide Abc class there is Test() method with Object class ,So it will come for execution.

    • Then it executes test() with object type inside “class Abc”.

    • System.out.println(guys.test(hello)); is a calling statement for the test() with” Long type”,as the “class Abc” consists of test() with Long type just execute it. So it doesn’t looks for the super type of Long type.

    Primitive data type Flow:

      javapadho
      Primitive data type Flow

    Example 6:

     
                    
                 class A
                 {
                    void test(long  l)
                    {
                       System.out.println(“Hi  long”);
                    }
                    void test(float i)
                    {
                       System.out.println(“Hi float”);
                    }
                    void  test(double obj)
                    {
                       System.out.println(“Hi  double”);
                    }
                    public static void main(String ram[])
                    {
                       A   a1= new  A();
                       Integer  i=Integer.valueOf(30);
                       a1.test(i);
                       a1.test(60.90);
                    }
                 }
                 class A
                 {
                    void test(long  l)
                    {
                       System.out.println(“Hi  long”);
                    }
                    void test(float i)
                    {
                       System.out.println(“Hi float”);
                    }
                    void  test(double obj)
                    {
                       System.out.println(“Hi  double”);
                    }
                    public static void main(String ram[])
                    {
                       A   a1= new  A();
                       Integer  i=Integer.valueOf(30);
                       a1.test(i);
                       a1.test(60.90);
                    }
                 }                

    Output:

    Hi long Hi double

    Explanation:

    • In the above program , a1.test(i) means it is a calling statement for test() with Integer type inside “class A”.

    • There is no test() with Integer type in “class A”, according to hierarchy of primitive datatype then its look for super type of same primitive datatype i.e,number type.

    • Then auto boxing is done automatically,later it looks for the primitive datatype with same type.,if it is not found then it looks for wider than that.

    • a1.test(60.90) is a calling statement for the test() with float type inside” class A” if it is available in class A its just executed.