According to the Java tutorial on autoboxing (and unboxing)
Converting a primitive value (an int, for example) into an object of the corresponding wrapper class (Integer) is called autoboxing. The Java compiler applies autoboxing when a primitive value is:
- Passed as a parameter to a method that expects an object of the corresponding wrapper class.
- Assigned to a variable of the corresponding wrapper class.
Converting an object of a wrapper type (Integer) to its corresponding primitive (int) value is called unboxing. The Java compiler applies unboxing when an object of a wrapper class is:
- Passed as a parameter to a method that expects a value of the corresponding primitive type.
- Assigned to a variable of the corresponding primitive type.
The tutorial further elaborates that operators like %
and +=
use intValue
to convert an Integer
to and int
at runtime.
What actually happens when you do a comparison like ==
, >
, or <
on a primitive and a wrapper class?
For example, if I do 5 == Integer.valueOf(5)
is 5
autoboxed and evaluated as Integer.valueOf == Integer.valueOf(5)
or is Integer.valueOf(5)
unboxed and evaluated as 5 == 5
.
In this example, the functional result is equivalent since Integer
s -128
to 127
are cached, but how about for larger numbers?
Empirical tests running this on larger numbers suggests that the Integer
object is unboxed and the comparison uses primitive values. Is there official documentation that defines this behavior specifically?