Wednesday, 24 May 2017

WRAPPER CLASS IN JAVA

By,
Santosh     
A class dedicated For each Java's eight primitive data types. Those are known as wrapper classes, because they "wrap" the primitive data type into an object of that class. Java.lang package contains all the wrapper classes , and they are imported by default into each Java programs.

In java wrapper class provides the mechanism to convert object type into primitive data type and primitive data type into object type .
Since J2SE 5.0, unboxing and autoboxing feature converts object type into primitive data type and primitive data type into object type automatically. Automatic conversion of primitive data type into object type is known as autoboxing and vice-versa unboxing.


Wrapper class:
1.Byte

2.Boolean
3.Character
4.Double
5.Float
6.Integer
7.Long
8.Short

Example : Primitive data type to Wrapper class
public class WrapperEx{  

public static void main(String [] args){  
//converting int data type into Integer object wrapper class  
int a=200;  
Integer b=Integer.valueOf(a);
Integer c=a;
//it’s a autoboxing, automatically compiler will write this line of code Integer.valueOf(a) internally  
 System.out.println(a+" "+b+" "+c);  
}
}  
Example: Wrapper class to Primitive data type
public class WrapperEx1{    

public static void main(String []args){    
Integer z=new Integer(3);
int x=z.intValue();
//Converting Integer object wrapper class to int data type
int y=z;
//it’s a unboxing, automatically now compiler will write this line of code internally z.intValue()     
    
System.out.println(z+" "+x+" "+y);    
}
}   
Automatic conversion by the Java compiler makes between the primitive data types to  the related  object wrapper classes is called as Autoboxing.

For example, changing a double to Double wrapper class , and an int to an Integer wrapper class, and so on.
Integer object_name = int veriable_name;
If the conversion goes the other way, this is called unboxing

int veriable_name =Interger object_name .intValue();

Table of Primitive type and Wrapper class:

Primitive type      Wrapper class
  boolean                   Boolean
     byte                         Byte
     char                      Character
     float                         Float
      int                          Integer
     long                          Long
    short                         Short
   double                     Double


2 comments:

  1. Wow Really Very nice post Such a useful information thanks for sharing Web hosting Company in Delhi

    ReplyDelete
  2. I really liked your blog post.Much thanks again. Awesome.
    java training

    ReplyDelete