Search code examples
pythonjavaboxingautoboxing

Does having a wrapper object return value (e.g. Integer) cause auto boxing in Java?


I couldn't find a definitive answer for this seemingly simple question. If I write a method like this:

public Integer getAnInt() {
  int[] i = {4};
  return i[0];
}

is the return value autoboxed into an Integer, or does it depend on what happens to the value after it's returned (e.g. whether the variable it is assigned to is declared as an Integer or int)?


Solution

  • Yes, boxed

    It will be (auto)boxed in the bytecode (.class file) because it's part of the public API, so other code might depend on the return value being an Integer.

    The boxing and unboxing might be removed at runtime by the JITter under the right circumstances, but I don't know if it does that sort of thing.