Forums Register Login

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

+Pie Number of slices to send: Send
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]
1
+Pie Number of slices to send: Send
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.
+Pie Number of slices to send: Send
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.
2
+Pie Number of slices to send: Send
 

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.
+Pie Number of slices to send: Send
Got it.
Thanks to both of you.
I am Arthur, King of the Britons. And this is a tiny ad:
a bit of art, as a gift, the permaculture playing cards
https://gardener-gift.com


reply
reply
This thread has been viewed 293 times.
Similar Threads
how to process the "java -verbose:class" output info in the command.
Convert a query string from one format to another
Constructor Chaining
Data truncation:incorrect date value:'null' for column
Problem with JDBC + mysql delete query
More...

All times above are in ranch (not your local) time.
The current ranch time is
Mar 28, 2024 12:12:05.