• Post Reply Bookmark Topic Watch Topic
  • New Topic
programming forums Java Mobile Certification Databases Caching Books Engineering Micro Controllers OS Languages Paradigms IDEs Build Tools Frameworks Application Servers Open Source This Site Careers Other Pie Elite all forums
this forum made possible by our volunteer staff, including ...
Marshals:
  • Campbell Ritchie
  • Tim Cooke
  • Ron McLeod
  • paul wheaton
  • Jeanne Boyarsky
Sheriffs:
  • Paul Clapham
  • Devaka Cooray
Saloon Keepers:
  • Tim Holloway
  • Roland Mueller
  • Himai Minh
Bartenders:

Integer Wrapper class comparison with == and !=

 
Greenhorn
Posts: 2
Eclipse IDE Tomcat Server Java
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • 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
 
author & internet detective
Posts: 42154
937
Eclipse IDE VI Editor Java
  • Likes 1
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • 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 Tomcat Server Java
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Thanks Jeanne
 
Java Cowboy
Posts: 16084
88
Android Scala IntelliJ IDE Spring Java
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • 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.
 
With a little knowledge, a cast iron skillet is non-stick and lasts a lifetime.
reply
    Bookmark Topic Watch Topic
  • New Topic