• Post Reply Bookmark Topic Watch Topic
  • New Topic

Integer Wrapper class comparison with == and !=  RSS feed

 
Abhijeet Seal
Greenhorn
Posts: 2
Eclipse IDE Java Tomcat Server
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi All,

I have following code :


It gives following output:

different objects
same object.

My question is why is i1!=i2 is true and i3 == i4 also true. because both i1 and i2 have same values and i3 and i4 have same values, so any one of the if conditions should be false .
I am confused here, please help.


Thanks,
Abhijeet
 
Jeanne Boyarsky
author & internet detective
Marshal
Posts: 37513
554
Eclipse IDE Java VI Editor
  • Likes 1
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Abhijeet,
Welcome to CodeRanch! This is a great question.

Java optimizes by reusing the same object for smaller numbers. Any Integer objects below 256 use the same object. That's why it works for 10. It is a number smaller than 256.
 
Abhijeet Seal
Greenhorn
Posts: 2
Eclipse IDE Java Tomcat Server
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Thanks Jeanne
 
Jesper de Jong
Java Cowboy
Sheriff
Posts: 16060
88
Android IntelliJ IDE Java Scala Spring
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Actually, it's not 256, as Jeanne says. Class Integer caches Integer objects with values between -128 and 127 (by default - it's possible to change this with a system setting).
Abhijeet Seal wrote:because both i1 and i2 have same values and i3 and i4 have same values, so any one of the if conditions should be false .

The == operator only checks if the things on the left and right side of the == refer to the exact same object. It does not look at the what value the object contains.
 
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!