Autoboxing lets Java automatically convert simple values like numbers into objects, so you don't have to do it yourself.
0
0
Autoboxing in Java
Introduction
When you want to store a simple number in a collection like ArrayList that only accepts objects.
When you want to pass a simple value to a method that expects an object.
When you want to mix simple values and objects without writing extra code to convert them.
When you want cleaner and easier-to-read code without manual conversions.
Syntax
Java
Integer obj = 10; // int 10 is autoboxed to Integer object Double dObj = 3.14; // double 3.14 is autoboxed to Double object
Autoboxing happens automatically when assigning a primitive value to its wrapper class.
Wrapper classes include Integer, Double, Boolean, etc., which are object versions of primitives.
Examples
line_end_arrow_notchHere, the int 5 is automatically converted to an Integer object.
Java
Integer num = 5; // int 5 autoboxed to Integer
line_end_arrow_notchThe double value 9.99 is automatically boxed into a Double object.
Java
Double price = 9.99; // double 9.99 autoboxed to Double
line_end_arrow_notchThe boolean true is automatically converted to a Boolean object.
Java
Boolean flag = true; // boolean true autoboxed to Boolean
Sample Program
This program shows autoboxing by adding int values directly to an ArrayList of Integer objects. Java converts the ints to Integer objects automatically.
Java
import java.util.ArrayList; public class AutoboxingExample { public static void main(String[] args) { ArrayList<Integer> numbers = new ArrayList<>(); // Autoboxing: int 10 is automatically converted to Integer object numbers.add(10); numbers.add(20); numbers.add(30); // Print all numbers for (Integer num : numbers) { System.out.println(num); } } }
OutputSuccess
Important Notes
line_end_arrow_notch
Autoboxing makes code simpler but can add small performance overhead because of object creation.
line_end_arrow_notch
Be careful when comparing wrapper objects with ==; use .equals() to compare values.
Summary
Autoboxing automatically converts primitive values to their wrapper objects.
It helps when working with collections or APIs that require objects.
Use autoboxing for cleaner and easier code without manual conversions.
