Found the following in my notes, but I am unable to make sense of it:
Primitive type wrapper classes implement caching for a limited number of value
First off: new Integer(0) == new Integer(0)
will never evaluate to true
, as new
always creates a new object, sidestepping any autoboxing-caching mechanism that might exist.
What you probably heard about was autoboxing (i.e. automatic conversion of primitive values to their respective wrapper classes when necessary). Autoboxing uses a mechanism that's also accessible using the wrapper classes valueOf()
methods. In other words: auto-boxing an int
to an Integer
works pretty much the same as calling Integer.valueOf(int)
.
Integer.valueOf(0) == Integer.valueOf(0)
will evaluate to true
, because common values (i.e. values with a low absolute value) are cached. You'll get the same Integer
object when you call valueOf(0)
twice in a row. This is not necessarily true with higher values (such as 666 in your example).