Nearby lessons

53 of 125

Java - 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
JCode Cell
1// Autoboxing: int -> Integer (automatic)
2Integer i = 10; // compiler writes Integer.valueOf(10)
3 
4// Unboxing: Integer -> int (automatic)
5int a = i; // compiler writes i.intValue()
6 
7// Works inside collections too
8ArrayList<Integer> list = new ArrayList<>();
9list.add(50); // autoboxed to Integer(50)
10int x = list.get(0); // unboxed back to int
11System.out.println(x);
📝 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 Questions
Progress: 0 / 2