What is Autoboxing in Java

Autoboxing and unboxing are introduced in Java 1.5 to automatically convert the primitive type into boxed primitive( Object or Wrapper class). autoboxing allows you to use primitive and object type interchangeably in Java in many places like an assignment, method invocation etc. If you have been using Collections like HashMap or ArrayList before Java 1.5 then you are familiar with the issues like you can not directly put primitives into Collections, instead, you first need to convert them into Object only then only you can put them into Collections. Wrapper class like Integer, Double and Boolean helps for converting primitive to Object but that clutter the code. With the introduction of autoboxing and unboxing in Java, this primitive to object conversion happens automatically by Java compiler which makes the code more readable.

But both autoboxing and unboxing come with certain caveats which need to be understood before using them in production code and it become even more important because they are automatic and can create subtle bugs if you are not sure when autoboxing  in Java code occurs and when unboxing happens.

This is my fifth article on features introduced in Java 5 after my post on Java Enum,  How Generics works in Java and varargs example. In this Java tutorial, we will see: What is autoboxing and unboxing in Java ?  When autoboxing and unboxing occur in Java? and things to remember while dealing with primitives and objects in Java with code examples.