![]() |
VOOZH | about |
A Wrapper class in Java is one whose object wraps or contains primitive data types. This leads to two key features: Autoboxing and Unboxing.
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.
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:
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
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
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
Sum of odd numbers = 50
| Primitive Type | Wrapper Class |
|---|---|
| boolean | Boolean |
| byte | Byte |
| char | Character |
| float | Float |
| int | Integer |
| long | Long |
| short | Short |
| double | Double |