11.02. Autoboxing and Unboxing

Autoboxing and Unboxing

  • Eclipse: Oxygen
  • Java: 1.8

In this tutorial, we will learn about what is autoboxing and unboxing. The ArrayList is very efficient, as we have seen, but it includes some more interesting features that are seen in this tutorial.

ArrayList only accepts the elements that are objects of a class such as an Integer class or any class defined by the user, but not for any primitive data type. Therefore, if we define the class as an Integer and not as a class defined by the user, then java automatically simplifies the work to create necessary new objects and the same while getting the value through indexing which we have to manually define while using a user-created class both of which examples are shown.

In the following example, ArrayList accepts the elements which are an object to a class such as an Integer class but not for any primitive data type.

We define the class as an Integer and it is autoboxed through method invocation. This is known as Autoboxing because in the following code conversion is taking place automatically.

In this program, we are creating a custom wrapper class and converting primitive data into an object manually.

While converting the object into a primitive data type is known as unboxing.

In this program, we are converting to double to a Double. If the conversion takes place automatically will be known as autoboxing. And if it goes in another way, will be known as unboxing.

In this program, we will show you how the programmer can code in a real environment. In which Java automatically performs autoboxing and unboxing.

Output

Contributed by: Poonam Tomar

Subscribe
Notify of
guest
0 Comments
Inline Feedbacks
View all comments