Amar Bessalah
Amar Bessalah

Reputation: 119

Java : Integer Immutability

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 ?

Upvotes: 2

Views: 369

Answers (4)

K.Rzepecka
K.Rzepecka

Reputation: 322

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.

Upvotes: 0

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!

Upvotes: 5

René Scheibe
René Scheibe

Reputation: 2080

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.

Upvotes: 1

Walter G.
Walter G.

Reputation: 155

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.

Upvotes: 0

Related Questions