• 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
  • Ron McLeod
  • Rob Spoor
  • Tim Cooke
  • Junilu Lacar
Sheriffs:
  • Henry Wong
  • Liutauras Vilda
  • Jeanne Boyarsky
Saloon Keepers:
  • Jesse Silverman
  • Tim Holloway
  • Stephan van Hulst
  • Tim Moores
  • Carey Brown
Bartenders:
  • Al Hobbs
  • Mikalai Zaikin
  • Piet Souris

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: 40747
827
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.
 
You showed up just in time for the waffles! And this tiny ad:
Building a Better World in your Backyard by Paul Wheaton and Shawn Klassen-Koop
https://coderanch.com/wiki/718759/books/Building-World-Backyard-Paul-Wheaton
reply
    Bookmark Topic Watch Topic
  • New Topic