Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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)?

like image 337
L. Blanc Avatar asked May 07 '26 10:05

L. Blanc


2 Answers

You are asking two different questions, and its important to separate them. The first is a language-level question: how does the language mediate the difference between int and Integer in a context such as return. The second is (by implication) a cost-model question -- will returning Integer cause useless heap allocation. Many developers conflate the two.

To the first question, you have a method that returns Integer but the operand of return is an expression of type int. A return is treated, essentially, as an assignment; you are trying to assign int to Integer. JLS 5.2 says that a boxing conversion is permitted in an assignment context. So yes, that int will be the subject of a boxing conversion.

But the fact that you are asking the question at all suggests that somehow you are scared of the performance overhead of boxing, hence the second, implied part of your question. Here is where it gets (a) murky, and (b) probably irrelevant. At runtime, whether heap allocation actually occurs depends on (a) whether the int is large (boxing caches the boxes for small integers) and (b) whether the method is inlined. If the method is inlined, the JIT will see that you are going int -> Integer -> int and elide the conversions.

And, even if boxing happens, does it really matter? How many billion-billion boxing operations would it take for this to show up on your performance metrics? Even if you pay the full cost of boxing, allocation and garbage collection of short-lived temporary objects is very cheap.

like image 125
Brian Goetz Avatar answered May 08 '26 23:05

Brian Goetz


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.

like image 20
Thomas Avatar answered May 08 '26 22:05

Thomas



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!