AutoBoxing and UnBoxing in Java
Introduction
In Java, AutoBoxing and UnBoxing are mechanisms that handle the automatic conversion between primitive data types and their corresponding wrapper classes. This feature simplifies coding by reducing the need for manual conversion.
Primitive Type | Wrapper Class |
---|---|
byte |
Byte |
short |
Short |
int |
Integer |
long |
Long |
float |
Float |
double |
Double |
char |
Character |
boolean |
Boolean |
What is AutoBoxing?
AutoBoxing is the automatic conversion of a primitive type into its corresponding wrapper class by the Java compiler.
Example of AutoBoxing:
int num = 10;
Integer obj = num; // AutoBoxing
Here, the primitive int
is automatically converted into an Integer
object.
What is UnBoxing?
UnBoxing is the automatic conversion of a wrapper class object into its corresponding primitive type.
Example of UnBoxing:
Integer obj = Integer.valueOf(50);
int num = obj; // UnBoxing
In this example, the Integer
object is automatically converted into an int
primitive.
AutoBoxing and UnBoxing in Expressions
Java allows AutoBoxing and UnBoxing in arithmetic and logical expressions.
public class AutoBoxingUnBoxingExample {
public static void main(String[] args) {
Integer a = 10;
Integer b = 20;
int sum = a + b; // AutoBoxing and UnBoxing occur here
System.out.println("Sum: " + sum);
}
}
AutoBoxing and UnBoxing in Collections
Since Java collections only work with objects, primitive types need to be converted into wrapper objects before storing them in collections.
import java.util.ArrayList;
public class WrapperCollectionExample {
public static void main(String[] args) {
ArrayList<Integer> numbers = new ArrayList<>();
numbers.add(100); // AutoBoxing
numbers.add(200);
int value = numbers.get(0); // UnBoxing
System.out.println("First Element: " + value);
}
}
Performance Considerations
While AutoBoxing and UnBoxing simplify code, they can also introduce performance overhead due to object creation.
Inefficient Code (Unnecessary AutoBoxing/UnBoxing):
Integer sum = 0;
for (int i = 0; i < 10000; i++) {
sum += i; // AutoBoxing and UnBoxing occur repeatedly
}
Optimized Code (Using Primitives):
int sum = 0;
for (int i = 0; i < 10000; i++) {
sum += i;
}
Using primitive types instead of wrapper classes avoids unnecessary object creation and improves performance.
Conclusion
AutoBoxing and UnBoxing are useful Java features that simplify working with primitive data types and wrapper classes. However, excessive usage in performance-sensitive areas can lead to unnecessary memory allocation and slow down execution. It is important to use these features efficiently to write clean and optimized Java code.
Sign up here with your email
ConversionConversion EmoticonEmoticon