Java supports automatic conversion of primitive types (int, float, double etc.) to their object equivalents (Integer, Float, Double etc.) in assignments, method and constructor invocations. This conversion is know as autoboxing.
Java also supports automatic unboxing, where wrapper types are automatically converted into their primitive equivalents if needed for assignments or method or constructor invocations.
Sample example :
i = new Integer(20); //Auto Unboxing
System.out.println(" i = " + i);
Java also supports automatic unboxing, where wrapper types are automatically converted into their primitive equivalents if needed for assignments or method or constructor invocations.
Sample example :
import java.util.ArrayList;
public class AutoboxingExample {
public static void main(String[] args) throws Exception {
int i = 10;
ArrayList list = new ArrayList();
list.add(new Integer(i)); // Without Autoboxing
list.add(i); // Autoboxing
System.out.println("List Size : " + list);
System.out.println(" i = " + i);
}
}
Note : It is not appropriate to use autoboxing and unboxing for scientific computing, or other performance-sensitive numerical code. An Integer
is not a substitute for an int
autoboxing and unboxing blur the distinction between primitive types and reference types, but they do not eliminate it.