Wrapper Class


Wrapper Class :

The wrapper class in Java provides the mechanism to convert primitive into object and object into primitive.


Primitive TypeWrapper class
booleanBoolean
charCharacter
byteByte
shortShort
intInteger
longLong
floatFloat
doubleDouble


Autoboxing

The automatic conversion of primitive data type into its corresponding wrapper class is known as autoboxing.

For example:- byte to Byte, char to Character, int to Integer, long to Long, float to Float, boolean to Boolean, double to Double, and short to Short.


  1. //Java program to convert primitive into objects  
  2. //Autoboxing example of int to Integer  
  3. public class WrapperExample1{  
  4. public static void main(String args[]){  
  5. //Converting int into Integer  
  6. int a=20;  
  7. Integer i=Integer.valueOf(a);//converting int into Integer explicitly  
  8. Integer j=a;//autoboxing, now compiler will write Integer.valueOf(a) internally  
  9.   
  10. System.out.println(a+" "+i+" "+j);  
  11. }}  


Unboxing

The automatic conversion of wrapper type into its corresponding primitive type is known as unboxing.

  1. //Java program to convert object into primitives  
  2. //Unboxing example of Integer to int  
  3. public class WrapperExample2{    
  4. public static void main(String args[]){    
  5. //Converting Integer to int    
  6. Integer a=new Integer(3);    
  7. int i=a.intValue();//converting Integer to int explicitly  
  8. int j=a;//unboxing, now compiler will write a.intValue() internally    
  9.     
  10. System.out.println(a+" "+i+" "+j);    
  11. }} 



Comments

Popular Posts