ProgrammingBackend Developer

Explain how the autoboxing and unboxing mechanism works in Java, what its risks are, and where it can lead to performance or logic errors.

Pass interviews with Hintsage AI assistant

Answer.

Autoboxing is the automatic conversion of primitive types (int, double, etc.) into their corresponding wrapper objects (Integer, Double, etc.). Unboxing is the reverse conversion of a wrapper object back to a primitive.

It works automatically during assignment, method parameters, and collections:

List<Integer> numbers = new ArrayList<>(); numbers.add(5); // Example of autoboxing: 5 (int) -> Integer(5) int value = numbers.get(0); // Unboxing: Integer(5) -> 5

Risks:

  • Possible NullPointerException during unboxing of null;
  • Inefficient use of memory and time due to constant object creation of wrappers;
  • Issues with == (reference comparison) and equals.

Trick Question.

Can the following code throw an exception? Why?

Integer x = null; int y = x;

Answer: The code throws a NullPointerException because when attempting to execute int y = x;, unboxing occurs from null to a primitive, and null cannot be converted to int.

Examples of real errors due to ignorance of topic nuances.


Story

Calculating sums in a collection of Integer wrappers. Every time the sum increased, a new Integer object was created, leading to significant delays on the production server instead of using int.

Story

A programmer used Integer as a key for caching, not considering that values -128...127 are cached, while others are not. Because of this, == suddenly started giving incorrect results, leading to incorrect data removal from the cache.

Story

In the REST API, nullable values came in. Simple unboxing of the incoming Integer sometimes caused crashes due to unexpected null instead of a number from the client.