1

A Wrapper Class is used to convert primitive into object and object into primitive. Similarly by using Autoboxing and Unboxing we can do the same then what is the difference in these two: 1-Concept wise 2-Code wise???

TheLostMind
  • 35,966
  • 12
  • 68
  • 104
abhishek shivdekar
  • 69
  • 1
  • 2
  • 11

2 Answers2

7

Auto-boxing and auto-unboxing is just the compiler silently helping you create and use primitive wrapper objects.

For example, the int primitive type has wrapper class called Integer. You wrap and unwrap as follows:

int myInt = 7;

// Wrap the primitive value
Integer myWrappedInt = Integer.valueOf(myInt);

// Unwrap the value
int myOtherInt = myWrappedInt.intValue();

With auto-boxing and auto-unboxing, you don't have to do all that boiler-plate stuff:

int myInt = 7;

// Wrap the primitive value
Integer myWrappedInt = myInt; // Compiler auto-boxes

// Unwrap the value
int myOtherInt = myWrappedInt; // Compiler auto-unboxes

It's just a syntactic sugar, handled by the compiler. The generated byte code is the same.

Andreas
  • 154,647
  • 11
  • 152
  • 247
0

Wrapper classes in java provides a mechanism to convert primitive into object and object into primitive. Whereas automatic boxing and unboxing allows you to do that conversion automatically. Autoboxing and auto unboxing are legal in java since Java 5.

public class Main {

    public static void main(String[] args) {
        int x=100;
        Integer iob;
        iob=x;//illegal upto JDK1.4
        iob= Integer.valueOf(x); //legal=> Boxing,Wrapping
        iob=x; //Legal since JDK1.5=> Auto Boxing

    }
}

Here x is a primitive variable, iob is a reference variable. So only an address can be assigned into this iob reference. iob=Integer.valueOf(x) will convert primitive integer into integer object. This conversion can be implied as wrapping. iob=x will do the same thing. It also saves a lot of coding.

public class Main {

    public static void main(String[] args) {
        Integer iob= new Integer(100);
        int x;

        x=iob;//illegal upto JDK1.4
        x=iob.intValue(); //unboxing,unwrapping

        x=iob; //legal since JDK1.5=> auto unboxing 

    }
}

Here iob.intValue() will take the value of integer object and it will assign that value into x. x=iob does the same thing except you don't need to write conversion code.

Sahan Amarsha
  • 2,176
  • 2
  • 14
  • 23