Hi Friends,
I have a doubt in accessing the memory address .
In java there is no pointers like c . then how can we access the address of the memory variable.
why do you want to?
Thanks sciwizeh for ur reply.
I need to fetch the memory address of the variable . In one article which i have read that "we cant say that we cant access the memory location".
Thanks sciwizeh for ur reply.
I need to fetch the memory address of the variable . In one article which i have read that "we cant say that we cant access the memory location".
Use the Object.toString() method to return the memory address.
public static void main(String... args){
Object o = new Object();
System.out.println(o.toString());
}
Note that it is a String representation of the memory address and not an accessible (or directly modifiable) memory address.
If we use toString() method to print the object ID then it is only print the reference ID not the object ID.
These posts are confusing variables and Objects. Remember that variables are either primitives (ints etc, not Objects) or reference variables (contain a reference to an Object); a variable is NOT an Object.
Object's toString() is not defined to return anything related to the address of the object, nor does it return anything related to a reference. The API doc is perfectly clear - it returns the class name and the objects hash code.
The toString method for class Object returns a string consisting of the name of the class of which the object is an instance, the at-sign character `@', and the unsigned hexadecimal representation of the hash code of the object. In other words, this method returns a string equal to the value of:
getClass().getName() + '@' + Integer.toHexString(hashCode())
The hashCode() method may return something relating to the address, but it's not guaranteed
As much as is reasonably practical, the hashCode method defined by class Object does return distinct integers for distinct objects. (This is typically implemented by converting the internal address of the object into an integer, but this implementation technique is not required by the JavaTM programming language.)
Having said all that, there is nothing in the Java language that corresponds to a memory address, and there is no syntax for accessing memory addresses.
If we use toString() method to print the object ID then it is only print the reference ID not the object ID.
This thread is from 2008. I'm posting to it just to correct errors in the replies in case anyone searches for this topic.
We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.