Hello! I have a question, this equality thing is driving me nuts....
Correct me If I'm wrong but in the following code I thought only oneString Object(at the lined marked //3) would be created on the heap, Given that the Literal is the same, right? Assuming that I further supposed that Both references, i and j referred the same String Object on the Heap.... So, my conclusion was that This little piece of code here Would Print true. But to my surprise... it outputs false
Could someone please give me all details of why This code outputs false?
My confusion is even greater than you imagine...because as you can see there's only one Integer Object instantiated. I thought that would play a role in this code's behavior, but it doesn't.
Best Regards, Jose [ April 09, 2008: Message edited by: Jose Campana ]
The problem is that the Integer class will create new Strings when it converts the integer into a String. New String, means different instances. So also both integers' value are equals, comparing their toString() with "==" will always be false.
[CV]: Yes, Actually, not "as if". It really is. How would you expect it to convert an integer into a String without creating a new instance ?
Well, it's possible to imagine an implementation that caches String objects for some commonly used numbers. Much like Integer.valueOf() caches Integer objects for ints in the range [-128, 127]. As it happens they don't do something like this in toString() - but they could. In general it's usually best not to assume anything about whether an object is a new object or a reused previously-existing object. Some methods may create new objects, and some may reuse them. Some may document which they do, and others may not. That's why we usually try to write code so it doesn't matter whether you get a new object or not - e.g. use equals() rather than == in most cases. [ April 09, 2008: Message edited by: Jim Yingst ]
Originally posted by Christophe Verre: The implementation could differ depending on the compiler provider
Doesn't have anything to do with the compiler, but with the runtime environment used to execute the code.
The soul is dyed the color of its thoughts. Think only on those things that are in line with your principles and can bear the light of day. The content of your character is your choice. Day by day, what you do is who you become. Your integrity is your destiny - it is the light that guides your way. - Heraclitus