Java logoJava/
JAVA-W1051

Boxing a value is redundant if it is immediately unboxedJAVA-W1051

Minor severityMinor
Performance categoryPerformance

A primitive is boxed, and then immediately unboxed. This probably is due to a manual boxing in a place where an unboxed value is required, thus forcing the compiler to immediately undo the work of the boxing.

Needless boxing and unboxing increases the number of dead objects that need to be garbage collected, and should be avoided.

Boxing can occur in the following cases:

  • Casting a primitive to a boxed type
  • Calling a boxed type's constructor with a primitive value (this is deprecated)
  • Calling a boxed type's valueOf method with a primitive value

Bad Practice

void checkValue(Integer value) {
    if (value > 4) {
        // ...
    }
}

// ...

int a = 3;

// a is boxed, but is immediately unboxed.
checkValue((Integer)a);

The generated bytecode for such a call looks like this:

iload_1                           // load `a` into the stack.
invokestatic  #7                  // call static method `Integer.valueOf()` with `a`
invokevirtual #13                 // call instance method `Integer.intValue()`
invokestatic  #17                 // call instance method `checkValue()` with `a`

Note that even though the code shows only a cast, javac outputs two calls, one to Integer.valueOf() to convert a into an Integer, then Integer.intValue() to convert it back into a primitive int.

Pass in the right argument type. In this case, we just need to pass a directly to checkValue.

checkValue(a);