Hmm, thats a tuffy.
I dont think (could be wrong) that it is possible to view the memory address of primitives(int, float,double, char).
You can try System.out.println(myObject) and as long as you have not overridden your toString() method, it always prints out some numbers. Methinks thats the memory address.
Test it out,
class Test{
public static void main(String args[]){
System.out.println(new Object());
}
}
SidTheSquid is partly right,
this is the memory address, but only for the Virtual Machine's memory.
But it's not working for primitives. I don't know any method, to get the address of a primitive. But i doubt, if this would be useful.
Where do you need the address for and what tybe are your variables?
Christoph
No, I don't need to use the address in a program right away... (Thank God! ) But being new to Java, I was trying to understand what it practically does in the memory. Your explanation was very useful.
If it's any help at all, my understanding is that Java invisibly keeps pointers in the stack, and all objects exist at the end of these pointers in the heap. This makes the memory address of anything but primitives slightly deceptive. I'm not sure whether printing the object gives you the pointer (stack) or object (heap) address, but in any event, it won't work the same way as C/C++. I'm not sure if primitives are kept on the stack or if they're managed like objects... ?
It's this arrangement that allows Java to do garbage collection and remove the need for memory allocation by the programmer. Objects on the heap that lose their stack pointer can be safely freed up. I believe the stack space for the pointers are allocated at compile time, but invoking the constructor with the new keyword is when heap space is allocated for the actual object. It's a pretty clever design, I think.
a few additions to segmentationfault's post:
The pointer printed is the pointer to the heap, but as this is java's heap it is of absolutely no use. The only thing is for comparing, if two object are the same instance.
Primitives are kept on the stack.
This site uses cookies to help personalise content, tailor your experience and to keep you logged in if you register.
By continuing to use this site, you are consenting to our use of cookies.