o9s
is a microblog
home archives search feed blogroll


Autoboxed Integer Reference Comparisons

for (int i = -138; i <= 138; i++) {
  Integer i1 = i;
  Integer i2 = i;

  if (i1 != i2) {
    System.out.println(i1 + " != " + i2);
  }
}

// Output:
// -138 != -138
// -137 != -137
// -136 != -136
// -135 != -135
// -134 != -134
// -133 != -133
// -132 != -132
// -131 != -131
// -130 != -130
// -129 != -129
// 128 != 128
// 129 != 129
// 130 != 130
// 131 != 131
// 132 != 132
// 133 != 133
// 134 != 134
// 135 != 135
// 136 != 136
// 137 != 137
// 138 != 138

Comparing autoboxed integer references will return true only when they’re in the range [-127, 128]. Why? Integers in this range are cached and re-used. Ideally the range would be bigger, but to not affect performance on limited devices, only 256 values are cached.

This is the sort of compromise Java needs to do because it’s a general-purpose programming language.

Posted on 2018-01-19   #java  






← Next post    ·    Previous post →