Autoboxing and Unboxing in Java

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 :

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);
i = new Integer(20); //Auto Unboxing
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 intautoboxing and unboxing blur the distinction between primitive types and reference types, but they do not eliminate it.
Enter your email address to get our daily JOBS & INTERVIEW FAQ's Straight to your Inbox.

Make sure to activate your subscription by clicking on the activation link sent to your email


Enter your email address to get our daily JOBS & INTERVIEW FAQ's Straight to your Inbox.

Make sure to activate your subscription by clicking on the activation link sent to your email