Last Updated:

Autopacking and unpacking in Java on an example

unpacking in Java

Autopacking in Java

Converting a primitive data type into an object of the corresponding wrapper class is called autopackaging. For example, converting an int to an Integer or converting long to a long object.

The Java compiler uses autopackaging for the following primitive values:

  • The primitive came in a method parameter that expects the object of the corresponding wrapper class. For example, you can pass int to a method with an Integer parameter—the Java compiler will convert int to An Integer.
  • Assign a value to the variable of the corresponding wrapper class. For example, a variable of type Long can take long.

Unpacking in Java

Assigning an object of a wrapper class to a variable of a primitive type. For example, a variable of type long can accept Long.

The Java compiler applies decompression in this case:

  • The wrapper class object has arrived in a method parameter that expects the value of the corresponding primitive type.
  • Assign a variable of a primitive type to the corresponding object of the wrapper class.

Here is a small Java program showing examples of autopacking and decompression in Java.

AutoboxingUnboxing.java

//package
package com.p-qc.autounbox;
import java.util.ArrayList;
import java.util.List;
public class AutoboxingUnboxing {
public static void main(String[] args) {
int i = 5;
long j = 105L;

//int came, so there will be a conversion to an Integer object
doSomething(i);

List<Long> list = new ArrayList<>();
//auto-boxing a primitive type into an appropriate wrapper class
list.add(j);
}
private static void doSomething(Integer in){
//unpacking, at runtime Integer.intValue()
int j = in;

//unboxing: passed Integer where int was expected
doPrimitive(in);
}
private static void doPrimitive(int i) {

}
}