I know there are similar posts on the topic, but they don\'t quite address my question. When you do:
Integer a = 10;
Integer b = 10;
System.out.println(\"a =
Please also note that the cache range was -128 to 127 in Java 1.5 but Java 1.6 onward it is the default range i.e. you can set upper value >= 127 by passing -XX:AutoBoxCacheMax=new_limit from command line
If you check the source you see:
/**
* Returns an Integer instance representing the specified int value. If a new
* Integer instance is not required, this method should generally be used in
* preference to the constructor Integer(int), as this method is likely to
* yield significantly better space and time performance by caching frequently
* requested values.
*
* @Parameters: i an int value.
* @Returns: an Integer instance representing i.
* @Since: 1.5
*/
public static Integer valueOf(int i) {
final int offset = 128;
if (i >= -128 && i <= 127) { // must cache
return IntegerCache.cache[i + offset];
}
return new Integer(i);
}
Source: link
It's the performance reasons why ==
returns boolean true with integers - it is totally a hack. If you want to compare values, then for that you have compareto
or equals
method.
In other languages, for example you can use ==
to compare strings as well, it is basically the same reason and it is called as one of the biggest mishaps of java language.
int
is a primitive type, predefined by the language and named by a reserved keyword. As a primitive it does not contain class or any class associated information. Integer
is an immutable primitive class, that is loaded through a package-private, native mechanism and casted to be Class - this provides auto boxing and was introduced in JDK1.5. Prior JDK1.5 int
and Integer
where 2 very different things.
Your first example is a byproduct of the spec requiring that flyweights be created in a certain range around 0. It should never, ever, be relied on.
As for why Integer
doesn't work like String
? I would imagine avoiding overhead to an already slow process. The reason you use primitives where you can is because they are significantly faster and take up way less memory.
Changing it now could break existing code because you're changing the functionality of the ==
operator.