0
0
JavaConceptBeginner · 3 min read

Autoboxing and Unboxing in Java: Simple Explanation and Examples

In Java, autoboxing is the automatic conversion of a primitive type (like int) to its corresponding wrapper class (like Integer). Unboxing is the reverse process, where the wrapper class is automatically converted back to the primitive type.
⚙️

How It Works

Imagine you have a box that can only hold objects, but you want to put simple things like numbers inside. Java has two types for numbers: primitive types (like int) and wrapper classes (like Integer) which are objects. Autoboxing is like Java automatically putting your simple number into a box (the wrapper object) when needed.

Unboxing is the opposite: when Java needs the simple number out of the box, it automatically takes it out. This makes it easy to mix simple numbers and objects without extra work from you.

💻

Example

This example shows autoboxing when a primitive int is assigned to an Integer object, and unboxing when the Integer is used as a primitive.

java
public class AutoBoxingExample {
    public static void main(String[] args) {
        Integer boxedNumber = 10; // Autoboxing: int 10 to Integer object
        int primitiveNumber = boxedNumber; // Unboxing: Integer object to int

        System.out.println("Boxed Number: " + boxedNumber);
        System.out.println("Primitive Number: " + primitiveNumber);
    }
}
Output
Boxed Number: 10 Primitive Number: 10
🎯

When to Use

Use autoboxing and unboxing when you want to work with collections like ArrayList that only accept objects, but you have primitive values. It saves you from manually converting between primitives and objects.

For example, if you want to store numbers in a list, autoboxing lets you add int values directly without creating Integer objects yourself. Unboxing helps when you retrieve these objects and want to use them as simple numbers.

Key Points

  • Autoboxing converts primitives to wrapper objects automatically.
  • Unboxing converts wrapper objects back to primitives automatically.
  • This feature reduces manual coding and makes code cleaner.
  • Introduced in Java 5 to improve ease of use with collections and APIs.

Key Takeaways

Autoboxing automatically wraps primitive types into their object wrappers.
Unboxing automatically extracts primitive values from wrapper objects.
These features simplify working with collections and APIs requiring objects.
Autoboxing and unboxing reduce the need for manual conversions in code.