Computer >> Computer tutorials >  >> Programming >> Java

Why do we need a wrapper class in Java?


A Wrapper class is a class which contains the primitive data types (int, char, short, byte, etc). In other words, wrapper classes provide a way to use primitive data types (int, char, short, byte, etc) as objects. These wrapper classes come under java.util package.

Why we need Wrapper Class

  • Wrapper Class will convert primitive data types into objects. The objects are necessary if we wish to modify the arguments passed into the method (because primitive types are passed by value).
  • The classes in java.util package handles only objects and hence wrapper classes help in this case also.
  • Data structures in the Collection framework such as ArrayList and Vector store only the objects (reference types) and not the primitive types.
  • The object is needed to support synchronization in multithreading.


Implementation of the wrapper class in Java

Autoboxing in Wrapper Class

Autoboxing is used to convert primitive data types into corresponding objects.

Example

public class AutoBoxingTest {
   public static void main(String args[]) {
      int num = 10; // int primitive
      Integer obj = Integer.valueOf(num); // creating a wrapper class object
      System.out.println(num + " " + obj);
   }
}

Output

10 10

Unboxing in Wrapper Class

Unboxing is used to convert the Wrapper class object into corresponding primitive data types.

Example

public class UnboxingTest {
   public static void main(String args[]) {
      Integer obj = new Integer(10); // Creating Wrapper class object
      int num = obj.intValue(); // Converting the wrapper object to primitive datatype
      System.out.println(num + " " + obj);
   }
}

Output

10 10