Reputation: 11
When I run the Java code again and again it prints different values of p
's address. Why is that?
Point code:
class Point {
}
Main Code:
public class HelloWorld
{
public static void main(String[] args) {
Point p = new Point();
System.out.println(p);
p = null;
System.gc();
}
}
Console Log:
test.Point@44585f2a
test.Point@5cfe174
test.Point@44585f2a
test.Point@44585f2a
test.Point@5cfe174
test.Point@44585f2a
Upvotes: 0
Views: 60
Reputation: 1280
That prints out getClass().getName() + '@' + Integer.toHexString(hashCode())
, not the address. Reference
Also, why would the address be the same every time you start the program? Some other process, any, could take up that spot in between program executions.
Also, I see you are invoking System.gc ();
Careful! It does not always do what one expect it to do! Reference
Upvotes: 4
Reputation: 122008
What you are seeing here (the toString implementation of object) is may not the actual address. It's identity hashcode of the object. That may or may not the actual address of the object in heap.
JVM moving the objects in the heap to different locations for several reasons hence the change in address.
Since you are assigning it to null, and the async call of Garbage collector may move the object to another part of heap.
Upvotes: 0