Autoboxing and Unboxing

Autoboxing: Converting primitive data type into Object of corresponding Wrapper class.

Unboxing: Converting Wrapper class object into corresponding primitive data type.

Example for Autoboxing:

AutoBoxing class: Define a method which receives an Integer arguement.

public class AutoBoxing {
    
    public void testAuto(Integer a){
        System.out.println("Wrapper class Integer "+ a);
    }
}

AutoAndUnBoxingTest class: When we call testAuto method with passing int argument compiler will convert it into Integer class.

public class AutoAndUnBoxingTest {
    public static void main(String args[]){
        AutoBoxing ab = new AutoBoxing();
        Integer a = 50000;
        int b = 50;
        ab.testAuto(a);
        ab.testAuto(b);
    }
}

Output:

Wrapper class Integer 50000
Wrapper class Integer 50

Example for Unboxing:

Unboxing Class: Define testAuto method which receives int argument.

public class Unboxing {
       public void testAuto(int a){
          System.out.println("Primitive type int "+ a);
      }
}

AutoAndUnBoxingTest Class: When we call testAuto method with passing Integer argument compiler will convert it into int.

public class AutoAndUnBoxingTest {
    public static void main(String args[]){
        Unboxing ub = new Unboxing();
        Integer a = 50000;
        int b = 50;
        ub.testAuto(a);
        ub.testAuto(b);
    }
}

Output:

Primitive type int 50000
Primitive type int 50

 

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s