Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java reference storage question

Tags:

java

reference

In java, when you pass an object to a method as a parameter, it is actually passing a reference, or a pointer, to that object because objects in Java are references.

Inside the function, it has a pointer to that object which is a location in memory. I am wondering where this pointer lives in memory? Is a new memory location created once inside the function to hold this reference?

like image 868
aab Avatar asked May 22 '10 16:05

aab


1 Answers

Within a function, a parameter reference is stored on the stack. The thing-referenced can live anywhere.

When some code calls a method, what normally happens is that space is made on the executing thread's stack, and this space is used to hold the parameters that are passed to the function. If one of the parameters "is an object", what's really in play is a reference to an object; that reference is copied onto the stack so that the called code can find it. It's important to recognize that the object itself is not copied, just the reference.

The prologue section of the called code will then typically allocate more space on the stack, for the method's own local variables, but underneath, the JVM has a pointer to the stack frame with all the parameters, so the called code can locate the object named by the parameter. Items created with 'new' will be allocated from the heap, and can persist even after the method exits, but all items allocated on the stack are dumped simply by moving the stack pointer back to where it was before the call.

like image 82
JustJeff Avatar answered Oct 19 '22 23:10

JustJeff