Does autoboxing call valueOf()?

Solution 1:

I first tought your question was a dupe of What code does the compiler generate for autoboxing?

However, after your comment on @ElliottFrisch I realized it was different :

I know the compiler behaves that way. I'm trying to figure out whether that behavior is guaranteed.

For other readers, assume that "behaves that way" means using valueOf.

Remember that there are multiples compilers for Java. To be "legal" they must follow the contract given in the JLS. Therefore, as long as all the rules here are respected, there is no guarantee of how autoboxing is internally implemented.

But I don't see any reason to not use valueOf, specially that it uses the cached values and is the recommended way as per this article by Joseph D. Darcy.

Solution 2:

Until the language specification mentions it, it is not guaranteed that autoboxing is equivalent to a call to the static valueOf methods. It is an implementation aspect, not part of the boxing conversion specification. An implementation is theoretically free to use another mechanism as long as it conforms to the rule you mentioned from the JLS.

In practice, there are many Sun JDK bug reports (e.g. JDK-4990346 and JDK-6628737) that clearly imply that when autoboxing was introduced in Java 5, the intention was having the compiler to rely on valueOf as stated in JDK-6628737:

The static factory methods Integer.valueOf(int), Long.valueOf(long), etc. were introduced in JDK 5 for javac to implement the caching behavior required by the autoboxing specification.

But that's only for javac, not necessarily all compilers.