Autoboxing in Java is the automatic conversion of a primitive data type (e.g., int, char, boolean) into its corresponding wrapper class object (e.g., Integer, Character, Boolean) by the Java compiler.
Example:
int num = 10; Integer numObj = num; // Autoboxing: int to Integer
In this example, the primitive int value num is automatically converted into an Integer object by the compiler.
Why is it useful?
- Ease of Use: Autoboxing allows developers to write cleaner and more readable code, as the conversion between primitives and objects is handled automatically.
- Collections Framework: Collections in Java (like
ArrayList,HashMap) work with objects, not primitive types. Autoboxing allows primitives to be easily used with these collections.