Java Unboxing

Introduction

In this lesson of Java course, we will learn abut the Java unboxing. Java Unboxing is converting a Wrapper class object to its corresponding primitive type. Wrapper classes, such as Integer, Long, Double., are used to wrap the primitive data types in an object, which makes it possible to use the primitives in collections and other object-oriented constructs. In this article, we’ll discuss the concept of unboxing, its use cases, and how it’s done in Java, with a complete example.

Java Unboxing?

Unboxing is converting a Wrapper class object to its corresponding primitive type. The primary purpose of Wrapper classes is to provide a way to represent primitives as objects. For example, converting an Integer object to int, Long to long, etc. Unboxing is the opposite of boxing, which is the process of converting a primitive data type to its corresponding Wrapper class.

Why do we need Unboxing?

There are several use cases where unboxing is required. For example, where the primitive value is required to perform mathematical operations, or when the value needs to be stored in a collection, or when it’s required to pass the primitive value as an argument to a method. Wrapper classes provide useful methods that can perform various operations, but sometimes these operations require the primitive value instead of the Wrapper class object. In such cases, unboxing is necessary.

How to perform Unboxing in Java?

Unboxing can be performed using the following methods:

  1. Using type casting: The Wrapper class object can be typecast to its corresponding primitive type. For example, the following code shows how an Integer object can be unboxed to int:
public void unboxingInteger() {
    Integer num = new Integer(10);
    int i = (int) num;
    System.out.println(i);
}
  1. Using the intValue(), longValue(), etc. methods: Each Wrapper class has a corresponding method to unbox its value. For example, the following code shows how an Integer object can be unboxed to int using the intValue() method:
public void unboxingIntegerUsingInbuiltMethod() {
    Integer num = new Integer(10);
    int i = num.intValue();
    System.out.println(i);
}

In the above example, we have created an Integer object and then used type casting to unbox it to int. The value of the Integer object is assigned to the primitive int variable. Finally, we have printed the value of the int variable to show unboxing.

Summary

Java Unboxing is an important concept in Java and is used to convert Wrapper class objects to their corresponding primitive type. Understanding this concept and its use cases is essential for any Java developer. The two methods discussed in this article, type casting, and using the value methods, are commonly used to perform unboxing in Java. You can find the source code for this Java course on GitHub repository.