I am bit confused as this question is asked in an interview and i said this: ""hashCode is generated for each object as and when it is created on the heap in the current running application""
but the interview said: "it is generated when we call hashcode method on the object"
More over, I am looking to understand the hashcode(and that too wrt to java) in more depth, please share some links/sources as it is asked extensively in some job interviews
PS: when i do sysout...on an object the output comes as employee@942f533
It depends what you mean here. As other answers mentioned, the function itself is not called when you create it. However,
90 * As much as is reasonably practical, the hashCode method defined by
91 * class {@code Object} does return distinct integers for distinct
92 * objects. (This is typically implemented by converting the internal
93 * address of the object into an integer, but this implementation
94 * technique is not required by the ... [JDK]
from http://www.docjar.com/html/api/java/lang/Object.java.html
Since the address of the object is assigned when it's created, you are correct in a sense. However, since it's not required, and many objects define an override, it's not necessarily true for all objects.
Usually in an interview, you have to challenge the interviewer a little bit to describe what you mean. If you do this and you're right, problem solved, if you do this and you're wrong, then you've at least shown you had a deeper understanding than what your original statment showed.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With