raj chiru wrote:My dout is which one will represent the memory address of the object whether toString()(Classname@19821f) or hashcode()?
Neither. The Javadoc for the Object class explains what both those vales represent.
The correct answer to your question is "don't know." When you are using a high-level language you avoid even knowing the memory addresses of anything. If you look at the Object class you get a hint, but it is only a hint and not definitive.
Remember that garbage collection may move the memory location of an object, so the hint given may give inaccurate information. You can get similar information with System#identityHashCode(java.lang.Object).
Thanks for your reply.
But i have one more dout i.e java is assign a hashcode based on the object's memory address on the heap, so what is need to generate the hashcode? and why can't you use the memory address value as a unique ID for object in place of hashcode value?
raj chiru wrote:But i have one more dout i.e java is assign a hashcode based on the object's memory address on the heap, so what is need to generate the hashcode? and why can't you use the memory address value as a unique ID for object in place of hashcode value?
Because the GC moves objects. And if the hashcode changes, when the object is used as a key in a hashing collection, it will corrupt the collection.
raj chiru wrote:Is there any way to find out memory address of the object?
Even if you could, it would be meaningless. As someone has pointed out, the GC can move objects around in memory.
How would you handle this:
int memAddress = <some theoretical call to get memory address>;
and unbeknownst to you, the GC runs in between those two lines of code, and moves stuff around. Now, you have your memAddress NOT POINTING AT THE OBJECT you think it's pointing to. In fact, it could be pointing to a different object entirely.
Further, what would you DO with the address? There is no pointer arithmetic (ala C/C++), you can't explicitly free it, copy into or from it... Java simply doesn't support that.