• 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
  • Jeanne Boyarsky
  • Ron McLeod
  • Paul Clapham
  • Liutauras Vilda
Sheriffs:
  • paul wheaton
  • Rob Spoor
  • Devaka Cooray
Saloon Keepers:
  • Stephan van Hulst
  • Tim Holloway
  • Carey Brown
  • Frits Walraven
  • Tim Moores
Bartenders:
  • Mikalai Zaikin

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: 41878
909
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.
 
Don't get me started about those stupid light bulbs.
reply
    Bookmark Topic Watch Topic
  • New Topic