Beware of boxing

164 words | Less than 1 minute to read

Boxing / Unboxing is when Java converts primitives to and from reference types, for example, converting between int and Integer types. This is often done automatically through the process known as autoboxing. There are three concerns when using reference types:

  1. Increased possibility of null pointer exceptions (compared with no possibility with primitives).
  2. Correctness (e.g. the equality operator == works differently for int and Integer).
  3. Performance considerations.

As noted in the Java Programming Language documentation:

It is not appropriate to use autoboxing and unboxing for scientific computing, or other performance-sensitive numerical code. An Integer is not a substitute for an int; autoboxing and unboxing blur the distinction between primitive types and reference types, but they do not eliminate it.

For these reasons, when we write API it is important that we consider the necessity of any API that returns or accepts reference types, as opposed to primitive types. Whenever possible, reference types should be replaced with primitive types.