How is unboxing performed in Java?

QuestionsQuestions8 SkillsProNumber, String and ArrayAug, 27 2025
0159

Unboxing in Java is the process of converting an object of a wrapper class back into its corresponding primitive type. This is done automatically by the Java compiler through a feature called autoboxing and unboxing, introduced in Java 5.

Example of Unboxing:

Here's a simple example demonstrating unboxing:

public class UnboxingExample {
    public static void main(String[] args) {
        // Creating a wrapper object
        Integer num = 100; // Autoboxing: Integer object created from int

        // Unboxing: Converting Integer object back to int
        int intValue = num; // Automatic conversion from Integer to int

        System.out.println("Integer value: " + num);
        System.out.println("Unboxed int value: " + intValue);
    }
}

Key Points:

  • In the example, num is an Integer object that holds the value 100.
  • When assigning num to intValue, Java automatically converts the Integer object to its primitive int type.
  • This process is seamless and does not require explicit casting.

Unboxing is particularly useful when working with collections (like ArrayList) that store objects, allowing you to retrieve primitive values easily.

0 Comments

no data
Be the first to share your comment!