Autoboxing and Unboxing in Java — Java Technical Interview Questions & Answers

Autoboxing and Unboxing in Java

Autoboxing and Unboxing in Java

  • Autoboxing converts primitive → wrapper automatically: Integer n = 10;. Unboxing is wrapper → primitive: int x = n;. Java does this so you can put int into ArrayList<Integer>.
  • Useful, but null is dangerous. Integer n = null; int x = n; throws NullPointerException.
  • Don’t rely on == between two Integer objects for large numbers — cache only covers a small range. Use equals.
  • Let's take this on the board with one tiny Main class — no extra files. Autoboxing and Unboxing in Java — 10 is boxed into Integer, then unboxed back to int for math. Start from main, go line by line, and stop at each print. That output is the proof for Autoboxing and Unboxing.

Technical Interview Tip: Show Integer n = 5; int x = n;. Then warn: null unboxing NPE.

Code Examples for Autoboxing and Unboxing in Java

Example

// Wrapper / autoboxing
public class Main {
  public static void main(String[] args) {
    Integer a = 10; // autobox
    int b = a;       // unbox
    System.out.println(a + b);
  }
}

Autoboxing and Unboxing in Java — 10 is boxed into Integer, then unboxed back to int for math.

How to Explain Autoboxing and Unboxing in Java to an Interviewer

What is autoboxing?

int → Integer automatically

What is the null trap?

Unboxing null Integer → NPE