what is boxing in java

1 year ago 82
Nature

Boxing in Java refers to the automatic conversion of primitive data types into their equivalent wrapper types. For example, converting an int to an Integer, a double to a Double, and so on. This allows primitives to be used where objects are required. The opposite operation, unboxing, converts an object type back into its primitive type.

Boxing and unboxing were introduced in Java 5.0. The Java compiler applies autoboxing when a primitive value is converted into an object of the corresponding wrapper class. For example, int to Integer. The Java compiler applies unboxing when an object of a wrapper class is converted to its corresponding primitive value. For example, Integer to int.

Boxing and unboxing can make programs slower and more memory-intensive. Wrapper classes for each primitive data type are provided in the java.lang package, namely Byte, Character, Double, Integer, Float, Long, Short, and Boolean.

Here are some examples of boxing and unboxing in Java:

// Boxing
int iPrimitive = 5;
Integer iWrapper = new Integer(iPrimitive); 

// Unboxing
iPrimitive = iWrapper.intValue();

Autoboxing and unboxing can also be used with comparison operators and method overloading.