Thursday, 6 October 2016

How to get address of an Object in Java?

Today we will look how to get address of an Object in Java. Generally if we have any object and we print the object, it will print the address of that Object.

But in case of String, if we create String object, and print the object it prints the value of String object instead of printing the address.

Therefore to get the address of any object we'll write one generic method which will return the address of the object.

To get the address of an Object we will use identityHashCode() method of System Class.

Here is the code snippet of the method -

public static String getObject(Object obj){
return obj.getClass().getName()+"@"+Integer.toHexString(System.identityHashCode(obj));
}

Now we have getObject() method which returns Address of an Object in java. 

Lets test the method -

public class FindObject {

public static String getObject(Object obj){
return obj.getClass().getName()+"@"+Integer.toHexString(System.identityHashCode(obj));
 }
public static void main(String args[]){
FindObject fO = new FindObject();

  System.out.println("Address without calling getObject method : "+fO);

  System.out.println("Address calling getObject method : "+getObject(fO));

  String str = new String("India");
  
  System.out.println("String str : "+str);

  System.out.println("Address of String str : "+getObject(str));
}
}

Output -

Address without calling getObject method : com.anjan.time.FindObject@15db9742
Address calling getObject method : com.anjan.time.FindObject@15db9742
String str : India
Address of String str : java.lang.String@6d06d69c

No comments:

Post a Comment