Home Java Java-get-example Java example program to get the object's ID
Questions:Ask|Latest

 
 

Share on Google+Share on Google+

Java example program to get the object's ID

Advertisement
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.

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
{
  public GetObjectId(){}
  public static void main(String args[]){
  String ind = new String("India");
  System.out.println("Hash code for String object: " 
 
+ ind.hashCode());
  GetObjectId getObj = new GetObjectId();
  System.out.println("Hash code for Class object: " 
  + getObj.hashCode
());
 }
}

Output:

C:\javaexamples>javac GetObjectId.java

C:\javaexamples>java GetObjectId
Hash code for String object: 70793495
Hash code for Class object: 4072869

Download Source Code

Advertisement

If you enjoyed this post then why not add us on Google+? Add us to your Circles



Liked it!  Share this Tutorial


Follow us on Twitter, or add us on Facebook or Google Plus to keep you updated with the recent trends of Java and other open source platforms.

Posted on: October 24, 2008

Related Tutorials

Ask Questions?    Discuss: Java example program to get the object's ID   View All Comments

Post your Comment


Your Name (*) :
Your Email :
Subject (*):
Your Comment (*):
  Reload Image
 
 
Comments
Renny
November 10, 2011
hash codes

>> But each object has its own unique hash value Not true. In theory many different objects can have the same hash code.
Andrzej
December 1, 2011
get the objects id?

You say hash value can be treated as the id for an object. This is true only as long as the hashCode method is not overwriten. Try your program on the following class: class NoIdObject { public int hashCode() { return 0; } }
DMCA.com