Saturday, January 11, 2020

Wrapper Classes

Wrapper classes in java

Wrapper classes in java are encapsulated primitive data types. boolean, char, float, double, long, int, byte and short all of these are primitive data types in Java. Java is Object Oriented Programming language and everything in java is supposed to be a Class, but for the performance purpose, these data types are not kept as Classes. There can be certain situations when we need to use these primitive data types as Classes only. Like we can not use primitive data types in Collections(ArrayList, LinkedList, Vectors, etc.) We can use wrapper classes of these primitive data types to handle such situations.


Class hierarchy for Wrapper classes.

Example:

public class WrapperDemo {
    public static void main(String[] args)
    {   //Integer Wrapper Class
        Integer i1=new Integer(10);
        Integer i2=new Integer("13");
        Integer i3=54;//Auto Boxing
        Integer i4=Integer.MAX_VALUE;
        Integer i5=Integer.MIN_VALUE;
        Integer i6=Integer.BYTES;
        Integer i7=Integer.valueOf(70);
        Integer i8=Integer.valueOf("70");
        System.out.println("i1="+i1);
        System.out.println("i2="+i2);
        System.out.println("i3="+i3);
        System.out.println("i4="+i4);
        System.out.println("i5="+i5);
        System.out.println("i6="+i6);
        System.out.println("i7="+i7);
        System.out.println("i8="+i8);
        Integer iObject=120;// Auto Boxing
        int iPrimitive=new Integer(25);//Un Boxing
       
    }

}
  Auto Boxing
Auto Boxing is the automatic conversion of a primitive value to a corresponding wrapper object.

 Integer iObject=120; // Auto Boxing 

 The assignment creates the appropriate Integer object itself.

Unboxing
Unboxing is the reverse conversion (called unboxing) also occurs automatically as needed.
int iPrimitive=new Integer(25); // unboxing

Video Tutorial