• Post Reply Bookmark Topic Watch Topic
  • New Topic

Why == doesn't behave the same with Double and Integer  RSS feed

 
Maurice Franck
Greenhorn
Posts: 10
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi guys,

Sorry for the newb question... I do understand why prints false while prints true (because == tests for value equality between two primitives, but for reference equality between two objects, and value1 and value2 are actually objects (of the class Double)), but then why prints true?

Since value5 and value6 are objects (of the class Integer), shouldn't == test for reference equality, thus return false? (like it does for value1 and value2 with the class Double)

Thanks in advance guys.

Have a great day ;-)


[fixed code tags]
 
Jeanne Boyarsky
author & internet detective
Marshal
Posts: 37496
548
Eclipse IDE Java VI Editor
  • Likes 1
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Maurice,
Howdy and welcome to CodeRanch! I've edited your post to fix the code tags. For future reference, note that you want the [/code] to appear after the block of code.

Anyway, the reason Integer behaves that way is an optimization. To avoid a proliferation of objects, Java has a cache of the smaller Integer objects. So they happen to test true for ==. You shouldn't rely on this behavior, but it is good to know it exists.

This shows how for bigger numbers, you do in fact get false with an Integer and ==.



For fun, try substituting 127 and then 128 for value5 and value6. You get to see the boundary for where caching stops.
 
Maurice Franck
Greenhorn
Posts: 10
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Thank you very much for the clear explanation Jeanne.
So if I understand correctly if an object of the class Integer has a value of type byte, even though it's an object == will actually test for value rather than reference.

Wanted to edit the title as Solved, but can't find an edit option.

Thanks anyway ;-)

Take care.
 
Carey Brown
Saloon Keeper
Posts: 3328
46
Eclipse IDE Firefox Browser Java MySQL Database VI Editor Windows
  • Likes 2
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Maurice Franck wrote:Thank you very much for the clear explanation Jeanne.
So if I understand correctly if an object of the class Integer has a value of type byte, even though it's an object == will actually test for value rather than reference.

No. Testing ANY object, Integer included, using == will only ever compare references and not their values.
Integer a = 7;
Integer b = 7;
Both a & b refer to the same cached object, hence, == return true.
 
Maurice Franck
Greenhorn
Posts: 10
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Got it.
Thanks to both of you.
 
It is sorta covered in the JavaRanch Style Guide.
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!