Because of the interning (Flyweight Pattern). This technique is usually perceived as a cache, And it’s even in a way, but the main advantage is sharing the state. Traditional cache has a slightly different concept, it can be invalidated, has restricted lifespan.
Java decided that small numbers should have this share because the object has a very high cost. A Integer
has more than 20 bytes of consumption. Probably if you didn’t need an object in these cases (Java 1x now has a mechanism that allows you to avoid expensive objects for small data, but it came a little late, has a very large code base using the objects).
Objects containing a value of 1 byte are already represented in the code by interning, then all the numbers 123
in objects (not to be confused with primitive, as is the int
) will be in the same memory position.
You may wonder why not do with objects that need 2 or 4 bytes. Only the 2-byte one would need at least 128KB (in practice it should exceed 1MB), not usually compensate since most will not be used.
Entering the field of opinion is that this should not be done, but until I understand that it fixes a little the problem that should not exist, should not use objects of more than 20 bytes to store such trivial information, or even objects should not occupy so much space, what would not solve but already help the problem.