«Back to Home

Core Java

Topics

Wrapper Class In Java

Wrapper Class
 
In Java, Wrapper class provides the concept to convert primitive into an object and an object into primitive. They "wrap" the primitive data type into an object of the class. Wrapper classes are a part of the java.lang package, which is imported by default into all Java programs.
 
Since Java 5, add new features of Java autoboxing and unboxing. These features convert automatically primitive into an object and object into primitive. The automatic conversion of primitive into an object is known as autoboxing and unboxing.
 
Use of Wrapper class in Java
  • To wrap primitive into an object. According to it, primitives can perform the activities reserved for the objects collection.

  • To provide a collection of utility functions for the primitives like converting primitive types to and from the string objects, converting to the various bases and comparing various objects.
In Java, eight classes of java.lang package are called as wrapper class. The list of eight wrapper classes is given below.

 Primitive Type  Wrapper class
 boolean  Boolean
 Char  Character
 Byte  Byte
 Short  Short
 Int  Integer
 Long  Long
 Float  Float
 double  Double

Wrapper class hierarchy as per Java API 

14
 
Let’s see an example of primitive to wrapper class, given below.
 
Code
  1. public class Calculator {  
  2.     public static void main(String args[]) {  
  3.         //Converting int into Integer    
  4.         int number = 500;  
  5.         Integer a = Integer.valueOf(number); //converting int into Integer    
  6.         Integer b = number; //autoboxing, now compiler will write Integer.valueOf(a) internally    
  7.         System.out.println(number + " " + a + " " + b);  
  8.     }  
  9. }  
15

Output

10

Let’s see an example of Wrapper class to primitive.
 
Code
  1. public class Calculator {  
  2.     public static void main(String args[]) {  
  3.         //Converting Integer to int      
  4.         Integer x = new Integer(25);  
  5.         int a = x.intValue(); //converting Integer to int    
  6.         int b = x; //unboxing, now compiler will write a.intValue() internally      
  7.         System.out.println(x + " " + a + " " + b);  
  8.     }  
  9. }  
12

Output

13

Summary

Thus, we learnt that Wrapper class provides the concept to convert primitive into object and object into primitive. We also learnt use of it in Java.