0

I have this code:

int i = 128;
Integer a = i;
Integer b = i;
System.out.println("a==i " + (a == i)); // true
System.out.println("b==i " + (b == i)); // true
System.out.println("a==b " + (a == b)); // false
System.out.println("equals ->"  + a.equals(i)
                                + b.equals(i)
                                + a.equals(b)); // true, true, true

Then I change my variable i to be 127 :

int i = 127;
Integer a = i;
Integer b = i;
System.out.println("a==i " + (a == i)); // true
System.out.println("b==i " + (b == i)); // true
System.out.println("a==b " + (a == b)); // true !!! look here
System.out.println("equals ->"  + a.equals(i)
                                + b.equals(i)
                                + a.equals(b)); // true, true, true

I don't understand, why "true" changed to "false"?

JuliaKo
  • 731
  • 1
  • 11
  • 19

1 Answers1

0

It is memory related

To save on memory, Java 'reuses' all the wrapper objects whose values fall in the following ranges:

All Boolean values (true and false)

All Byte values

All Character values from \u0000 to \u007f (i.e. 0 to 127 in decimal)

All Short and Integer values from -128 to 127.

Long values between -128 and 127.

Community
  • 1
  • 1
  • Also `Long` values between -128 and 127. – Peter Lawrey Feb 26 '16 at 08:57
  • @PeterLawrey ty for the comment. where can I find that stated about Long. is that in Java 7? – Developer Marius Žilėnas Feb 26 '16 at 09:01
  • The Javadoc says "public static Long valueOf(long l) Returns a Long instance representing the specified long value. If a new Long instance is not required, this method should generally be used in preference to the constructor Long(long), as this method is likely to yield significantly better space and time performance by caching frequently requested values. Note that unlike the corresponding method in the Integer class, *this method is not required to cache values within a particular range*." – Peter Lawrey Feb 26 '16 at 09:04
  • But the source says; public static Long valueOf(long l) { final int offset = 128; if (l >= -128 && l <= 127) { // will cache return LongCache.cache[(int)l + offset]; } return new Long(l); } – Peter Lawrey Feb 26 '16 at 09:04
  • @PeterLawrey ty. due to boxing unboxing the following example works not identical for int and long. `Long l128 = 128L; Long l1 = 128L; Long l2 = 128L; System.out.println(l1 == l2); Integer i128 = 128; Integer i1 = i128; Integer i2 = i128; System.out.println(i1 == i2);` prints **false true**. and if we use primitives `long l128 = 128L; Long l1 = 128L; Long l2 = 128L; System.out.println(l1 == l2); int i128 = 128; Integer i1 = i128; Integer i2 = i128; System.out.println(i1 == i2);` prints **false false** . =o – Developer Marius Žilėnas Feb 26 '16 at 09:16
  • That is to be expected. The Integer cache can be larger as per the Javadoc for Integer.valueOf. – Peter Lawrey Feb 26 '16 at 09:19
  • @PeterLawrey ok, thanks :). – Developer Marius Žilėnas Feb 26 '16 at 09:20