Nearby lessons
53 of 125Java - Autoboxing and Unboxing
📌 What You Will Learn
- Why wrapper classes exist
- How to convert primitive to object and object to primitive
- Autoboxing and unboxing (automatic conversion)
- Important methods: valueOf, parseXxx, toString, xxxValue
- The famous Integer caching (range -128 to 127)
Autoboxing and Unboxing is a core concept of the Java language. This lesson explains Autoboxing and Unboxing (Java 5 onwards) with complete, runnable code examples, clear step-by-step explanations, and common mistakes to avoid with exam-style MCQs at the end.
Autoboxing and Unboxing (Java 5 onwards)
From Java 5, this conversion became automatic:
- Autoboxing — primitive to wrapper object, done automatically.
- Unboxing — wrapper object to primitive, done automatically.
In simple words: Autoboxing and unboxing are automatic conversions done by the compiler. Integer i = 10; really writes Integer.valueOf(10), and int a = i; really writes i.intValue().
Example01
📝 Key Takeaways
- Wrapper classes box each primitive into an object: int->Integer, char->Character, etc.
- Autoboxing converts primitive to wrapper automatically; unboxing does the reverse.
- parseInt returns primitive int; valueOf returns Integer object.
- Use equals() not == for wrapper objects and Strings.
- Integer values from -128 to 127 are cached, so == can be true for small values.
- Collections can store only objects, so wrappers are essential there.
🧠 Test Your Knowledge
2 QuestionsProgress: 0 / 2