• 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
  • Paul Clapham
  • Tim Cooke
  • Jeanne Boyarsky
  • Liutauras Vilda
Sheriffs:
  • Frank Carver
  • Henry Wong
  • Ron McLeod
Saloon Keepers:
  • Tim Moores
  • Frits Walraven
  • Tim Holloway
  • Stephan van Hulst
  • Carey Brown
Bartenders:
  • Al Hobbs
  • Piet Souris
  • Himai Minh

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: 41250
849
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.
 
I child proofed my house but they still get in. Distract them with this tiny ad:
the value of filler advertising in 2021
https://coderanch.com/t/730886/filler-advertising
reply
    Bookmark Topic Watch Topic
  • New Topic