Wrapper class

Wrapper class in java provides the mechanism to convert primitive into object and object into primitive.
Since J2SE 5.0, autoboxing and unboxing feature converts primitive into object and object into primitive automatically. The automatic conversion of primitive into object is known and autoboxing and vice-versa unboxing.
One of the eight classes of java.lang package are known as wrapper class in java. The list of eight wrapper classes are given below:
Primitive TypeWrapper class
booleanBoolean
charCharacter
byteByte
shortShort
intInteger
longLong
floatFloat
doubleDouble

Wrapper class Example: Primitive to Wrapper

  1. public class WrapperExample1{  
  2. public static void main(String args[]){  
  3. //Converting int into Integer  
  4. int a=20;  
  5. Integer i=Integer.valueOf(a);//converting int into Integer  
  6. Integer j=a;//autoboxing, now compiler will write Integer.valueOf(a) internally  
  7.   
  8. System.out.println(a+" "+i+" "+j);  
  9. }}  
Output:
20 20 20

Wrapper class Example: Wrapper to Primitive

  1. public class WrapperExample2{    
  2. public static void main(String args[]){    
  3. //Converting Integer to int    
  4. Integer a=new Integer(3);    
  5. int i=a.intValue();//converting Integer to int  
  6. int j=a;//unboxing, now compiler will write a.intValue() internally    
  7.     
  8. System.out.println(a+" "+i+" "+j);    
  9. }}    
Output:
3 3 3

1 comment:


  1. Thanks, this is generally helpful.
    Still, I followed step-by-step your method in this Java online training
    Java online course

    ReplyDelete