I've read everywhere that when you define an Integer between -128 to 127 in Java, instead of creating a new object it returns an object already created.
I don't see any point of doing this other than letting newbie programmers compare Integer objects with ==
to see if they are the same number, but I think this is bad because sure they think that they can compare any Integer with ==
, and also is teaching a bad practice in any programming language: comparing the content of two 'different' objects with ==
.
Is there any other reason on why this is done? Or is it just a bad decision when designing the language (In my point of view) like optional semicolon in JavaScript?
EDIT: I see here that they explain the behaviour: Why does the behavior of the Integer constant pool change at 127?
I'm asking why they designed it to have this behaviour, and not why is this behaviour happening.
I think that creating any object takes more time than taking it from the symbol table. Moreover, if I am not mistaken, every object on the heap takes up 24 bytes of additional space for the header. Now, if a programmer writes his/her program, most of the operations are done on small ints (in this case, small Integers). So it allows to save a lot of space and to improve performance a little.
It's called the Flyweight pattern and is used to minimize memory usage.
Those numbers are very likely to be used repeatedly, and autobox types like
Integer
are immutable (note this is done not just forInteger
). Caching them makes it so there aren't lots of instances and reduces GC (Garbage Collection) work as well.The JLS covers this in 5.1.7. Boxing Conversion specifically by saying: