VOOZH about

URL: https://www.geeksforgeeks.org/java/autoboxing-unboxing-java/

⇱ Autoboxing and Unboxing in Java - GeeksforGeeks


  • Courses
  • Tutorials
  • Interview Prep

Autoboxing and Unboxing in Java

Last Updated : 2 Aug, 2025

A Wrapper class in Java is one whose object wraps or contains primitive data types. This leads to two key features: Autoboxing and Unboxing.

1. Autoboxing

The automatic conversion of primitive types to the object of their corresponding wrapper classes is known as autoboxing. For example: conversion of int to Integer, long to Long, double to Double, etc. 

2. Unboxing

It is just the reverse process of autoboxing. Automatically converting an object of a wrapper class to its corresponding primitive type is known as unboxing. For example, conversion of Integer to int, Long to long, Double to double, etc. 

Example 1: Java program to illustrate the Concept of Autoboxing and Unboxing

Output:

👁 Image

Let's understand how the compiler did autoboxing and unboxing in the example of Collections in Java using generics.

Example 2: Java Program to Illustrate Autoboxing


Output
ArrayList: [1, 2, 24]

Explanation: 

In the above example, we have created a list of elements of the Integer type. We are adding int primitive type values instead of Integer Object and the code is successfully compiled. It does not generate a compile-time error as the Java compiler creates an Integer wrapper Object from primitive int i and adds it to the list. 

Example 3: Java Program to Illustrate Autoboxing


Output
true
true
true
true
true
true
true
true
true
true

Another example of auto and unboxing is to find the sum of odd numbers in a list. An important point in the program is that the operators remainder (%) and unary plus (+=) operators do not apply to Integer objects. But still, code compiles successfully because the unboxing of Integer Object to primitive int value is taking place by invoking intValue() method at runtime. 

Example 4: Java Program to Illustrate Find Sum of Odd Numbers using Autoboxing and Unboxing


Output
Sum of odd numbers = 50

Java Primitive Types and Their Wrapper Classes

Primitive TypeWrapper Class
booleanBoolean
byteByte
charCharacter
float Float
int Integer
longLong
short Short
doubleDouble
Comment
Article Tags: