Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations strongm on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

Memory address

Status
Not open for further replies.

sheila11

Programmer
Dec 27, 2000
251
US
Hi all,

I am new to Java. Is it possible to get the memory address of a variable, the way we can get it in C or C++?

Thanks,
Sheila
 
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());
}
}

my output was:
java.lang.Object@3f5d07


Hope this helps
 
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
 
Thanks, SidTheSquid & 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.

Thanks,
Sheila
 
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.

Christoph
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top