Java Autoboxing and Unboxing
Java can insert a conversion between a primitive and its wrapper when a context allows it. Boxing wraps a value, and unboxing obtains the primitive value again. The convenience does not remove the effects of null, overload selection, or object identity.
- Primitive types
- Reference types
Primitive types include:
byte
short
int
long
float
double
char
booleanWrapper classes represent these primitive types as objects:
| Primitive Type | Wrapper Class |
|---|---|
byte | Byte |
short | Short |
int | Integer |
long | Long |
float | Float |
double | Double |
char | Character |
boolean | Boolean |
Java provides automatic conversion between primitives and their corresponding wrapper classes.
These conversions are called:
- Autoboxing — primitive → wrapper object
- Unboxing — wrapper object → primitive
What is Autoboxing?
Autoboxing is the automatic conversion of a primitive value into its corresponding wrapper class object.
For example:
int number = 10;
Integer value = number;Here Java automatically converts:
int → IntegerConceptually, this is similar to:
Integer value = Integer.valueOf(number);Simple Autoboxing Example
public class HelloWorld {
public static void main(String[] args) {
int number = 100;
Integer wrapper = number;
System.out.println(wrapper);
}
}Output
100The variable:
int numberis a primitive.
The variable:
Integer wrapperis a reference type.
Java automatically performs the conversion.
What is Unboxing?
Unboxing is the automatic conversion of a wrapper object into its corresponding primitive type.
Example
Integer wrapper = 100;
int number = wrapper;Here Java automatically converts:
Integer → intConceptually, this is similar to:
int number = wrapper.intValue();Simple Unboxing Example
public class HelloWorld {
public static void main(String[] args) {
Integer wrapper = 100;
int number = wrapper;
System.out.println(number);
}
}Output
100Autoboxing and Unboxing Together
Both operations can be used in the same program.
public class HelloWorld {
public static void main(String[] args) {
int a = 10;
// Autoboxing
Integer b = a;
// Unboxing
int c = b;
System.out.println(a);
System.out.println(b);
System.out.println(c);
}
}Output
10
10
10The conversion flow is:
Autoboxing
int ----------------> Integer
|
|
Unboxing
|
↓
intWhy Was Autoboxing Introduced?
Before Java 5, developers had to manually convert between primitive values and wrapper objects.
For example:
int number = 10;
Integer wrapper = Integer.valueOf(number);To convert back:
int value = wrapper.intValue();Java 5 introduced autoboxing and unboxing to make these conversions automatic.
Instead of:
Integer wrapper = Integer.valueOf(number);we can write:
Integer wrapper = number;Instead of:
int value = wrapper.intValue();we can write:
int value = wrapper;This makes Java code easier to write and read.
Autoboxing with Different Primitive Types
Autoboxing works with all primitive types that have wrapper classes.
public class HelloWorld {
public static void main(String[] args) {
byte b = 10;
short s = 20;
int i = 30;
long l = 40L;
float f = 50.5f;
double d = 60.5;
char c = 'A';
boolean flag = true;
Byte byteValue = b;
Short shortValue = s;
Integer intValue = i;
Long longValue = l;
Float floatValue = f;
Double doubleValue = d;
Character charValue = c;
Boolean booleanValue = flag;
System.out.println(byteValue);
System.out.println(shortValue);
System.out.println(intValue);
System.out.println(longValue);
System.out.println(floatValue);
System.out.println(doubleValue);
System.out.println(charValue);
System.out.println(booleanValue);
}
}Output
10
20
30
40
50.5
60.5
A
trueUnboxing Different Wrapper Types
The reverse operation is also supported.
public class HelloWorld {
public static void main(String[] args) {
Byte b = 10;
Short s = 20;
Integer i = 30;
Long l = 40L;
Float f = 50.5f;
Double d = 60.5;
Character c = 'A';
Boolean flag = true;
byte byteValue = b;
short shortValue = s;
int intValue = i;
long longValue = l;
float floatValue = f;
double doubleValue = d;
char charValue = c;
boolean booleanValue = flag;
System.out.println(byteValue);
System.out.println(shortValue);
System.out.println(intValue);
System.out.println(longValue);
System.out.println(floatValue);
System.out.println(doubleValue);
System.out.println(charValue);
System.out.println(booleanValue);
}
}Output
10
20
30
40
50.5
60.5
A
trueAutoboxing with Collections
One of the most important uses of autoboxing is with Java collections.
Collections work with objects, not primitive types.
This is invalid:
ArrayList<int> numbers = new ArrayList<>();Instead, use the wrapper class:
ArrayList<Integer> numbers = new ArrayList<>();Then:
numbers.add(10);Here 10 is an int, but the list expects Integer.
Java automatically performs autoboxing.
Example
import java.util.ArrayList;
public class HelloWorld {
public static void main(String[] args) {
ArrayList<Integer> numbers = new ArrayList<>();
numbers.add(10);
numbers.add(20);
numbers.add(30);
System.out.println(numbers);
}
}Output
[10, 20, 30]Conceptually:
numbers.add(10);works similarly to:
numbers.add(Integer.valueOf(10));Unboxing from Collections
When retrieving an Integer from a collection and assigning it to an int, Java performs unboxing.
Example
import java.util.ArrayList;
public class HelloWorld {
public static void main(String[] args) {
ArrayList<Integer> numbers = new ArrayList<>();
numbers.add(100);
Integer wrapper = numbers.get(0);
int number = numbers.get(0);
System.out.println(wrapper);
System.out.println(number);
}
}Output
100
100The expression:
numbers.get(0)returns an Integer.
When assigned to:
int numberJava automatically unboxes it.
Autoboxing in Method Arguments
Autoboxing can occur when passing a primitive to a method expecting a wrapper object.
Example
public class HelloWorld {
static void display(Integer number) {
System.out.println(number);
}
public static void main(String[] args) {
int value = 50;
display(value);
}
}Output
50The method expects:
Integerbut we provide:
intJava automatically boxes the value.
Unboxing in Method Arguments
The reverse can also happen.
public class HelloWorld {
static void display(int number) {
System.out.println(number);
}
public static void main(String[] args) {
Integer value = 50;
display(value);
}
}Output
50The method expects:
intbut the argument is:
IntegerJava automatically unboxes the value.
Autoboxing in Return Values
Autoboxing can also happen when returning a value from a method.
Example
public class HelloWorld {
static Integer getNumber() {
int number = 100;
return number;
}
public static void main(String[] args) {
Integer result = getNumber();
System.out.println(result);
}
}Output
100The method return type is:
Integerbut the method returns an int.
Java automatically boxes the value.
Unboxing in Return Values
Unboxing can also happen when the method return type is primitive.
public class HelloWorld {
static int getNumber() {
Integer number = 100;
return number;
}
public static void main(String[] args) {
System.out.println(getNumber());
}
}Output
100The Integer value is automatically unboxed to int.
Autoboxing in Expressions
Wrapper objects can participate in arithmetic operations because Java automatically unboxes them.
Example
public class HelloWorld {
public static void main(String[] args) {
Integer a = 10;
Integer b = 20;
int result = a + b;
System.out.println(result);
}
}Output
30Conceptually:
Integer a → int
Integer b → int
↓
addition
↓
intUnboxing and Arithmetic
Consider:
Integer number = 10;
int result = number * 5;Java automatically unboxes number.
Example
public class HelloWorld {
public static void main(String[] args) {
Integer number = 10;
int result = number * 5;
System.out.println(result);
}
}Output
50Autoboxing with Assignment
Consider:
Integer number = 10;The value:
10is an int literal by default.
Java boxes it into an Integer.
Conceptually:
Integer number = Integer.valueOf(10);Unboxing with Assignment
Consider:
Integer number = 10;
int value = number;Conceptually:
int value = number.intValue();Important: null and Unboxing
One of the most important problems with unboxing is null.
Consider:
Integer number = null;
int value = number;This causes:
NullPointerExceptionWhy?
Because Java needs to obtain the primitive value from the Integer object.
Conceptually:
int value = number.intValue();But:
number == nullTherefore, there is no object from which Java can obtain the primitive value.
Example of NullPointerException
public class HelloWorld {
public static void main(String[] args) {
Integer number = null;
int value = number;
System.out.println(value);
}
}Result
Exception in thread "main" java.lang.NullPointerExceptionSafe approach
Check for null before unboxing:
public class HelloWorld {
public static void main(String[] args) {
Integer number = null;
if (number != null) {
int value = number;
System.out.println(value);
}
}
}Autoboxing and Wrapper Caching
Java may reuse certain wrapper objects, particularly for commonly used values.
For example:
Integer a = 100;
Integer b = 100;
System.out.println(a == b);This can print:
truebecause the same cached Integer object may be reused.
However, this should not be used to compare wrapper values.
Always use:
equals()for value comparison.
Example
Integer a = 1000;
Integer b = 1000;
System.out.println(a.equals(b));Output
trueThe important rule is:
== → compares references for objects
equals() → compares values when the class implements value-based equalityAutoboxing and Method Overloading
Autoboxing can affect which overloaded method Java chooses.
Example
public class HelloWorld {
static void display(int value) {
System.out.println("int method");
}
static void display(Integer value) {
System.out.println("Integer method");
}
public static void main(String[] args) {
int a = 10;
Integer b = 20;
display(a);
display(b);
}
}Output
int method
Integer methodJava chooses the method that directly matches the argument type when possible.
Primitive Widening vs Autoboxing
This is an important concept in method resolution.
Suppose:
static void display(long value) {
System.out.println("long");
}
static void display(Integer value) {
System.out.println("Integer");
}Now:
int number = 10;
display(number);Java can either:
int → longthrough primitive widening, or:
int → Integerthrough boxing.
In method invocation, Java generally prefers applicable conversions such as primitive widening before boxing.
Therefore, understanding the different conversion phases is important when working with overloaded methods.
Boxing Does Not Mean Casting
Autoboxing and casting are different concepts.
Casting
double value = 10.5;
int number = (int) value;This converts:
double → intAutoboxing
int number = 10;
Integer value = number;This converts:
int → IntegerSo:
Casting → type conversion between compatible types
Autoboxing → primitive → corresponding wrapper
Unboxing → wrapper → corresponding primitiveExplicit Boxing
Instead of relying on autoboxing:
Integer number = 10;you can explicitly use:
Integer number = Integer.valueOf(10);Both produce an Integer.
For example:
public class HelloWorld {
public static void main(String[] args) {
int number = 10;
Integer a = number;
Integer b = Integer.valueOf(number);
System.out.println(a);
System.out.println(b);
}
}Output
10
10Explicit Unboxing
Instead of:
Integer number = 10;
int value = number;you can explicitly write:
int value = number.intValue();Example
public class HelloWorld {
public static void main(String[] args) {
Integer number = 100;
int a = number;
int b = number.intValue();
System.out.println(a);
System.out.println(b);
}
}Output
100
100Autoboxing with Conditional Expressions
Autoboxing and unboxing can also appear in conditional expressions.
For example:
public class HelloWorld {
public static void main(String[] args) {
Integer a = 10;
Integer b = 20;
int result = true ? a : b;
System.out.println(result);
}
}Output
10The selected Integer value can be unboxed when assigned to the primitive int.
Conditional expressions involving primitives and wrappers can have additional type rules, so it is important to check the types of both operands rather than assuming the result type.
Autoboxing with for Loops
Wrapper values can be automatically unboxed when used in primitive contexts.
Example
import java.util.ArrayList;
public class HelloWorld {
public static void main(String[] args) {
ArrayList<Integer> numbers = new ArrayList<>();
numbers.add(10);
numbers.add(20);
numbers.add(30);
for (int number : numbers) {
System.out.println(number);
}
}
}Output
10
20
30Each Integer retrieved from the collection is automatically unboxed to int.
Complete Example
The following example demonstrates both autoboxing and unboxing with a collection.
import java.util.ArrayList;
public class HelloWorld {
public static void main(String[] args) {
// Primitive value
int number = 100;
// Autoboxing
Integer wrapper = number;
// Collection requires objects
ArrayList<Integer> numbers = new ArrayList<>();
numbers.add(number);
// Retrieve wrapper object
Integer value = numbers.get(0);
// Unboxing
int result = value;
System.out.println("Primitive: " + number);
System.out.println("Wrapper: " + wrapper);
System.out.println("Collection: " + numbers);
System.out.println("Unboxed value: " + result);
}
}Output
Primitive: 100
Wrapper: 100
Collection: [100]
Unboxed value: 100Advantages of Autoboxing and Unboxing
1. Less Code
Without autoboxing:
Integer number = Integer.valueOf(10);With autoboxing:
Integer number = 10;2. Easier Collection Usage
Instead of manually boxing every value:
numbers.add(Integer.valueOf(10));
numbers.add(Integer.valueOf(20));we can write:
numbers.add(10);
numbers.add(20);3. Better Readability
The code becomes simpler and easier to understand.
4. Better Integration Between Primitive and Object APIs
Java APIs can use wrapper types while application code can continue working naturally with primitive values.
Disadvantages and Things to Consider
1. Additional Object Overhead
Wrapper objects are reference types, while primitives are generally more lightweight.
For performance-sensitive numerical processing, primitives are often preferable when objects are not required.
2. Possible NullPointerException
Unboxing a null wrapper can cause:
NullPointerException3. Unexpected Behavior with ==
Wrapper objects should generally be compared using:
equals()rather than:
==when comparing values.
4. Hidden Conversions
Autoboxing and unboxing happen automatically, which can sometimes make the actual conversion less obvious.
For example:
Integer a = 10;
int b = a;contains two different type representations even though the code looks simple.
Common Mistakes
Mistake 1: Unboxing null
Integer value = null;
int number = value;This causes NullPointerException.
Mistake 2: Comparing wrappers with ==
Avoid:
Integer a = 1000;
Integer b = 1000;
System.out.println(a == b);Use:
System.out.println(a.equals(b));when both references are known to be non-null.
Mistake 3: Thinking all conversions are boxing
This:
int a = 10;
long b = a;is not autoboxing.
It is primitive widening:
int → longAutoboxing would be:
Integer b = a;Mistake 4: Thinking casting and boxing are the same
This:
int number = (int) 10.5;is casting.
This:
Integer number = 10;is autoboxing.
Mistake 5: Using wrappers unnecessarily
If an object is not required, a primitive can often be more appropriate.
For example:
int total = 0;may be preferable to:
Integer total = 0;for simple numerical calculations.
Autoboxing vs Unboxing
| Feature | Autoboxing | Unboxing |
|---|---|---|
| Conversion | Primitive → Wrapper | Wrapper → Primitive |
| Example | Integer x = 10; | int x = integer; |
| Automatic | Yes | Yes |
| Common use | Collections, object APIs | Arithmetic, primitive APIs |
Can fail due to null | No | Yes |
| Example method | Integer.valueOf() | intValue() |
Explicit Conversion vs Automatic Conversion
| Operation | Explicit Form | Automatic Form |
|---|---|---|
int → Integer | Integer.valueOf(x) | Integer y = x |
Integer → int | x.intValue() | int y = x |
double → Double | Double.valueOf(x) | Double y = x |
Double → double | x.doubleValue() | double y = x |
char → Character | Character.valueOf(x) | Character y = x |
Character → char | x.charValue() | char y = x |
Key Points
- Autoboxing means converting a primitive into its corresponding wrapper object automatically.
- Unboxing means converting a wrapper object into its corresponding primitive automatically.
- Autoboxing was introduced in Java 5.
intis wrapped byInteger.doubleis wrapped byDouble.charis wrapped byCharacter.booleanis wrapped byBoolean.- Autoboxing is especially useful with collections and generics.
- Unboxing allows wrapper objects to participate in primitive operations.
- Unboxing a
nullwrapper causesNullPointerException. - Use
equals()rather than==for comparing wrapper values. Integer.valueOf()is an explicit way to obtain anInteger.intValue()is an explicit way to extract anintfrom anInteger.- Boxing is different from primitive widening and casting.
- Although automatic conversion is convenient, unnecessary wrapper usage can add object and performance overhead.
Conclusion
Autoboxing and unboxing provide automatic conversion between Java primitive types and their corresponding wrapper classes.
Autoboxing
int number = 10;
Integer value = number;int → IntegerUnboxing
Integer value = 10;
int number = value;Integer → intThese features are particularly important when working with Java Collections, Generics, method parameters, return values, and APIs that require objects.
The most important thing to remember is:
Autoboxing:
Primitive → Wrapper
Unboxing:
Wrapper → PrimitiveAnd always be careful with:
Integer value = null;
int number = value;because unboxing a null wrapper reference results in a NullPointerException.
See you in next page....🙂