Interview kitsBlog

Your dream job? Lets Git IT.
Interactive technical interview preparation platform designed for modern developers.

XGitHub

Platform

  • Categories

Resources

  • Blog
  • About the app
  • FAQ
  • Feedback

Legal

  • Privacy Policy
  • Terms of Service

© 2026 LetsGit.IT. All rights reserved.

LetsGit.IT/Categories/Java
Javamedium

Autoboxing/unboxing — what is it and what are common pitfalls?

Tags
#autoboxing#wrapper#npe
Back to categoryPractice quiz

Answer

Autoboxing converts primitives to wrappers (e.g., `int`→`Integer`) and unboxing does the reverse. Pitfalls: unboxing `null` causes NPE, `Integer` caching can confuse `==`, and extra allocations can hurt performance in hot code.

Integer x = null;
// int y = x; // NullPointerException due to unboxing

Integer a = 100;
Integer b = 100;
System.out.println(a == b); // true (Integer cache)

Integer c = 1000;
Integer d = 1000;
System.out.println(c == d); // false

Advanced answer

Deep dive

Autoboxing/unboxing is compiler-generated conversion between primitives and wrapper types.

Where it shows up:

  • Generics: `List<Integer>` can’t store `int`.
  • APIs that use `Object`.

Common pitfalls

  • NPE on unboxing:
Integer x = null;
int y = x; // NPE
  • `==` on wrappers compares references (and caches can hide the bug):
Integer a = 127, b = 127; // cached
Integer c = 128, d = 128; // usually not cached
System.out.println(a == b); // true
System.out.println(c == d); // false
  • Performance: repeated boxing in hot loops creates garbage and slows GC.

Practical guidance

  • Prefer primitives in hot code paths.
  • Use `.equals()` for wrappers, or unbox explicitly when safe.
  • Consider primitive streams / specialized collections when needed.