Java example program to get the object's ID
java get Object id
In java there is no any specific method that provides us the object's ID. But each object has its own unique hash value which can be treated as unique Id for that object.
To explain this concept here we are getting the hash code for the two object and this can be done by using the hashCode() method on both of the created objects.
String ind = new String("India");
System.out.println("Hash code for String object: "
+ ind.hashCode());
Above line of code creates a new String object "ind" and its hash code can be get by the method hashCode().
GetObjectId getObj = new GetObjectId();
System.out.println("Hash code for Class object: "
+ getObj.hashCode());
In above lines we have created a new object of GetObjectId and for its hash code we will be using hashCode() method. Here is the full example code of GetObjectId.java as follows:
GetObjectId.java
public class GetObjectId
|
Output:
C:\javaexamples>javac GetObjectId.java C:\javaexamples>java GetObjectId Hash code for String object: 70793495 Hash code for Class object: 4072869 |