Friday, July 24, 2020

Wrapper Classes in Java Programming (Boxing and Unboxing)

Wrapper Class:
    A Wrapper class is a class whose object wraps or contains a primitive data types. We can wrap a primitive value into a wrapper class object. We can also convert a wrapper object to the primitive data type.

Why and When need of wrapper classes ?
  
1. The classes in java.util package handles only objects and hence wrapper classes help in this case also. When we use Generics of Collection Framework, such as LinkedList, ArrayList, Vector, etc. we have to use Wrapper classes and not primitive types.

for ex.
    ArrayList<Integer> obj = new ArrayList<Integer>();
   
   here, we can not use int primitive data type we have to use Integer wrapper class.

2. When we use any web based form then there we use String for numbers but we have to convert that numbers into the integer format then we use wrapper class there.

for ex.
    String s = "+919898989898";
   
    int i = Integer.parseInt(s);
    suppose above number is an contact number but it is in string type we have to convert it into int type then we can convert it using Integer wrapper class.
   
3. An object is needed to support synchronization in multithreading.

Wrapper Classes List:


  • Boxing : conversion of primitive types to the object.
    for ex.
             int a = 10;
            Integer obj = new Integer(a);    // 1st way for conversion
             Integer obj2 =Integer.valueOf(a);    //2nd way for conversion

  • AutoBoxing : Automatic conversion of primitive types to the object.
      for ex.
             int a = 10;
             Integer obj3 = a;   //way for conversion
  • Unboxing : converting an object of a wrapper class to its corresponding primitive type is known as unboxing.
        for ex.
        Integer obj = 500;
        int u = obj.intValue();
  • AutoUnboxing : Automatic converting an object of a wrapper class to its corresponding primitive type is known as AutoUnboxing.
         for ex.
        Integer obj = 500;
        int u1= obj;


For better Explanation Watch the video.......

No comments:

Post a Comment

Happy Birthday Priya Using Python Turtle Graphics

Happy Birthday Priya Using Python Turtle Graphics.... import  turtle  as  tech_habit from turtle import * from random import randint ankita ...