Wrapper classes



We have discussed few classes in previous posts. Lets get in to this topic. You know that Java is object oriented language. So Java see everything as an objects. In Scanner class we got user input as objects. Like this Java see all the things as objects. Wrapper classes are used to convert simple data types (byte,short,int,long,float,double char,boolean) into objects. 

Why we need to convert data types to objects ?

  • You need to convert primitives to objects, if you want to use data structures in Java. They only allows objects.
  • If you want to use collections, you have to use objects not primitives.
  • Other thing is, objects can be assigned to null and it can be send null parameters to methods or constructors. To do this thing you have to use objects. It cannot be done with primitives.


    What are the wrapper classes ?

    Wrapper classes can wrap primitives to objects and also remove the wrap from objects. Think about a gift. 

    The gifts are wrapped. But you have to unwrap it to see what inside.
    Wrapper classes are like them. It provides methods to wrap and unwrap them. 

    Why we need to use wrapper classes ?

    In Java, wrapper classes produces two things.

    • Provide the procedure to wrap primitive data types to objects.
    • Provide an assortment of utility functions to primitives. 
    When you are using collections like List, Set, Map...etc they allows objects as their elements.


    Wrapper classes for primitive values




    You can see wrapper classes are belongs to java.lang package. So you need not to import it. Simply wrapper class name is same as primitive name except char. But primitives begin with lower case. 


    How to create wrapper objects ?

    There are three approaches to create wrapper objects in Java.

    1. Using wrapper constructors
    2. Using valueOf() methods
    3. Using wrapper conversion utilities.


    1.Creating wrapper objects using wrapper constructors.

    As to above graph you can see, each wrapper classes provide two constructors except Character type. One for its primitive type and other one for its String representation.



    public class WrapperClassTest {
            public static void main(String args[]){
      
                   int x=10;
      
                   Integer x1 = new Integer(10);
                   Integer x2 = new Integer("100");
      
                   System.out.println(x1);
                   System.out.println(x2); 
            }
    }
    
    
    


    2.Creating wrapper objects using valueOf() methods.

    This is the second method to create wrapper classes. 

    • This is a static method. So it can be invoked directly on the class. 
    • In this method there are two forms. 

    Form 1

    • In this method it takes the value of specify primitive (int, float, double...etc) and assign it to its wrapper object type. 
    • In following example you can see that I assign value 10 to integer type object x.


    public class WrapperClassTest {
           public static void main(String args[]){
      
                  Integer x = Integer.valueOf(10);
        
                  System.out.println(x);
           }
    }
    
    
    

    Form 2


    • In this method, there are two parameters(value and radix).
    • This radix indicates in what base the first argument is represented. 
    • In following example I converted "10110" to three integer objects.


    public class WrapperClassTest {
           public static void main(String args[]){
      
                   Integer x1 = Integer.valueOf("10110", 2);
                   Integer x2 = Integer.valueOf("10110", 8);
                   Integer x3 = Integer.valueOf("10110", 16);
        
                   System.out.println("Decimal value of 10110    : " + x1);
                   System.out.println("Octal value of 10110      : " + x2);
                   System.out.println("Hexadecimal value of 10110: " + x3);
           }
    }
    
    
    


    3. Creating wrapper objects using wrapper conversion utilities.


    In Java we use some methods to do this task.

    • xxxValue()
    • parseXxx() 
    • toString()
    • toXxxString()


    xxxValue() method


    This method is used to convert wrapped numeric value into another primitive type. So there are six no arg methods. Try following example to understand about this method.



    public class WrapperClassTest {
           public static void main(String args[]){
      
                    Integer x = new Integer(10);
      
                    byte b = x.byteValue();
                    short s = x.shortValue();
                    long l = x.longValue();
                    float f = x.floatValue();
                    double d = x.doubleValue();
      
                    System.out.println(b);
                    System.out.println(s);
                    System.out.println(l);
                    System.out.println(f);
                    System.out.println(d);
      
           }
    }
    
    
    

    parseXxx() method

    This method is used to represent the primitive data type of a String. Either you can one argument or two arguments like following example.


    public class WrapperClassTest {
            public static void main(String args[]){
    
                   int i1 = Integer.parseInt("100");
                   int i2 = Integer.parseInt("10110", 2);
      
                   System.out.println(i1);
                   System.out.println(i2);
      
            }
    }
    
    
    

    You may get confuse about the different between this method ( parseXxx() ) and valueOf() methods.


    • valueOf() - This method returns a newly created wrapper object.
    • parseXxx() - This returns the primitive value of given value.

    toString() method

    This method is used to get the String representation of a numerical object. Try these simple programs to understand about this method.

    public class WrapperClassTest {
            public static void main(String args[]){
      
                    Integer x = 100;
                    String s = x.toString();
      
                    System.out.println(x.toString());
                    System.out.println(s);
                    System.out.println(Integer.toString(1000));
            }
    }
    
    
    

    toXxxString() method
     
    This method is used to convert base 10 numbers of Integer and Long to base 2, 8 or 16. t can be used as follows.


    public class WrapperClassTest {
            public static void main(String args[]){
      
                     System.out.println(Integer.toBinaryString(10));
                     System.out.println(Integer.toOctalString(10));
                     System.out.println(Integer.toHexString(10));
      
                     System.out.println(Long.toBinaryString(100));
                     System.out.println(Long.toOctalString(100));
                     System.out.println(Long.toHexString(100));
      
            }
    }
    
    

    Do you know, Wrapper objects are Immutable

    Wrapper classes are immutable classes, it means the value of wrapper object cannot be changed once you initialized it. This is like String immutability. Try this program.

    public class WrapperClassTest {
           public static void main(String args[]){
      
                   Integer x = 100;
                   Integer y = x++;
      
                   if(x==y){
                          System.out.println("x = y"); 
                   }
                   else{
                          System.out.println("x != y");
                   }
           }
    }
    
    
    


    Special note about Wrapper classes



    I move on Boxing, Un-boxing,  Auto boxing and Auto Un-boxing in next post.
    Wrapper classes Wrapper classes Reviewed by Ravi Yasas on 1:17 PM Rating: 5

    No comments:

    Powered by Blogger.