Does autoboxing call valueOf()?

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.

Leave a Comment