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 ?

3
  • possible duplicate of this Commented Feb 6, 2017 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) Commented Feb 6, 2017 at 21:52
  • 1
    In Java, "AB" == "AB"; but "AB" != "A" + "B". Commented Feb 6, 2017 at 21:57

4 Answers 4

5

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!

Sign up to request clarification or add additional context in comments.

1 Comment

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.
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.

Comments

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.

Comments

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.