Codes :
Integer a1 = 100;
Integer a2 = 100;
System.out.println(a1 == a2); // true
Integer b1 = new Integer(100);
Integer b2 = new Integer(100);
System.out.println(b1 == b2); // false
Integer c1 = 150;
Integer c2 = 150;
System.out.println(c1 == c2); // false
Java designs that when using AutoBoxing, values between -128 and 127 appear to refer to the same Integer objects, which causes different results of the first code fragments and the last one
My question is : Why does java design it like this, are there any advantages ?
The simple rationale is that it’s useful/efficient to have a set of Integers already created and available for boxing. It’s very likely that if an application will need boxed integers, they’re going to be in a certain range (e.g. 1… whatever). The fact that they’re boxed up to -127/128 is a simple design heuristic based upon what’s likely to provide benefit without pre-boxing a huge number of integers.