Question about Java storage

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

Inside the function, it has a pointer to this object, which is a place in memory. I wonder where this pointer lives in memory? Is a new memory cell created once inside a function to store this link?

+6
java reference
source share
4 answers

Inside the function, a reference to the parameter is stored on the stack. The specified thing can live anywhere.

When some code calls a method, it usually happens that the space is executed on the stack of the executable thread, and this space is used to store the parameters that are passed to the function. If one of the parameters "is an object", then what really plays is a reference to the object; this link is copied onto the stack so that the called code can find it. It is important to recognize that the object itself is not copied, but only a link.

The prolog section of the called code then usually allocates more space on the stack for its own local variables of the method, but below it the JVM has a pointer to the stack frame with all the parameters, so the called code can find an object called the parameter. Elements created using the "new" will be allocated from the heap and can be saved even after the method exits, but all elements allocated on the stack are reset simply by moving the stack pointer to where it was before the call.

+2
source share

Objects are not links, but you use links everywhere. eg.

String a = "abc"; 

the a is a reference to a String . Therefore, links are distributed everywhere. Are they pointers? Not. A link is more like an object handle. JVM has the right to move objects in memory. The pointer must change to reflect this. Link does not. A link can be modeled as a pointer to a pointer.

0
source share

Each parameter of the function passed by value - however, the parameter is not an object, but instead is a link.

So, the same object exists with two references to it.

 String s = "my string"; // reference to this object created doSomething(s); // in the doSomething function, a new reference to the same point of memory is passed by value 

This means that when I have my void doSomething(String str) function, I work the same way as outside the function, except that I have another link. The same object referenced, but with a different link. Therefore, if inside my function I do str = "different string"; , which will not change, ss still points to the same memory point as all this time, but now str instead of indicating that points to points, now indicates where the "different line" is stored.

0
source share

for example, in JFrame you can start like this:

 public myFrame mF; public void Panel1(myFrame mF) { your code ... } 
0
source share

All Articles