in , ,

Java autoboxing and unboxing

Java autoboxing and unboxing
Java autoboxing and unboxing

In this tutorial, we will learn about Java autoboxing and unboxing with the help of examples.

Java Autoboxing – Primitive Type to Wrapper Object

In autoboxing, the Java compiler automatically changes over primitive sorts into their relating covering class objects. For instance,

int a = 56;

// autoboxing
Integer aObj = a;

Autoboxing has a great advantage while working with Java collections.


Example 1: Java Autoboxing

import java.util.ArrayList;

class Main {
   public static void main(String[] args) {

      ArrayList<Integer> list = new ArrayList<>();

      //autoboxing
      list.add(5);
      list.add(6);

      System.out.println("ArrayList: " + list);
   }
}

Output

ArrayList: [5, 6]

In the above example, we have made an array list of Integer type. Henceforth the array list can just hold objects of Integer type.

Notice the line,

list.add(5);

Here, we are passing primitive sort value. However, due to autoboxing, the primitive value is automatically changed over into an Integer object and stored in the array list.


Java Unboxing – Wrapper Objects to Primitive Types

In unboxing, the Java compiler automatically changes over covering class objects into their relating primitive sorts. For instance,

// autoboxing
Integer aObj = 56;

// unboxing
int a = aObj;

Like autoboxing, unboxing can likewise be used with Java assortments.


Example 2: Java Unboxing

import java.util.ArrayList;

class Main {
   public static void main(String[] args) {

      ArrayList<Integer> list = new ArrayList<>();

      //autoboxing
      list.add(5);
      list.add(6);

      System.out.println("ArrayList: " + list);

      // unboxing
      int a = list.get(0);
      System.out.println("Value at index 0: " + a);
   }
}

Output

ArrayList: [5, 6]
Value at index 0: 5

In the above example, notice the line,

int a = list.get(0);

Here, the get() strategy returns the object at index 0. In any case, due to unboxing, the object is automatically changed over into the primitive sort int and relegated to the variable a.


Thanks for reading! We hope you found this tutorial helpful and we would love to hear your feedback in the Comments section below. And show us what you’ve learned by sharing your photos and creative projects with us.

salman khan

Written by worldofitech

Leave a Reply

Java Type Casting

Java Type Casting

How to Encrypt a USB Drive in Windows 10

Step by step instructions to Encrypt a USB Drive in Windows 10