2

I found this in a book :

The Integer objects are immutable objects. If there is an Integer object for a value that already exists, then it does not create a new object again.

I tried an exemple :

Integer i = 2147483645;
Integer j=2147483644;
j++;

System.out.println("i == j : "+(i==j));;
System.out.println("i.equals(j) : "+i.equals(j));

I'm getting False , True .

Shouldn't I get True , True ?

luk2302
  • 55,258
  • 23
  • 97
  • 137
  • possible duplicate of [this](http://stackoverflow.com/questions/3637936/java-integer-equals-vs) – Sasi Kathimanda Feb 06 '17 at 21:51
  • 9
    Your book is inaccurate. Auto-boxing (which is what turns the int literal into an Integer) is only required to cache values from -128 to +127 (see [jls 5.1.7](http://docs.oracle.com/javase/specs/jls/se8/html/jls-5.html#jls-5.1.7)) – yshavit Feb 06 '17 at 21:52
  • 1
    In Java, "AB" == "AB"; but "AB" != "A" + "B". – Elliott Frisch Feb 06 '17 at 21:57

4 Answers4

4

Shouldn't I get True,True.???

no, you get false since those objects are not stored in any integer pool (more or less the same principle as string-pool), and therefore i and j are pointing to a totally different reference.

there is a possible case where you can get such a comparing returning true, and that is for values until 127...

one example to verify that is:

 Integer b2=128;
 Integer b3=128;
 System.out.println(b2==b3);

that will print false.

but this

Integer b2=127;
Integer b3=127;
System.out.println(b2==b3);

will print true!

ΦXocę 웃 Пepeúpa ツ
  • 47,427
  • 17
  • 69
  • 97
  • The Integer cache size can depend on the JVM and your command like args so I use `-129` in examples which is never cached. `128` might be. – Peter Lawrey Feb 06 '17 at 22:12
1

Integers in Java are only object-identical for values -128 to 127 to meet the Java spec for boxing/unboxing - see this author's post https://blogs.oracle.com/darcy/entry/boxing_and_caches_integer_valueof.

René Scheibe
  • 1,970
  • 2
  • 14
  • 20
0

If you write:

Integer i = 2147483645;
Integer j = 2147483644;
j++;

then you create two independent Objects in two places in memory. Checking their equality with "==", you check if place in memory is the same. And you receive false because it isn't. Using "equals" you check if their value is the same, and it is.

K.Rzepecka
  • 322
  • 2
  • 9
0

There's a difference between using the == and the equals, cause the first one compares the reference and second compares the value. So to answer your question first one is false cause the reference is not the same (are not pointing to the same object), versus the second which is comparing the value and that's why it returns true.

Walter G.
  • 135
  • 4
  • 12