Where is the java reference variable stored?

How is the Java reference variable stored? Does this work look like a C pointer?

what do I mean by the reference variable myDog in this code

Dog myDog = new Dog(); 

I understood about the C-pointer, it stores on the heap if a global variable, and stores the local variable on the stack. I am surprised that java works the same way.

+6
source share
6 answers

You need to understand the slightly lower levels of Java memory organization. Primitives (int, double, boolean, etc.) and links to objects pointing to the heap are saved on the stack.

Inside any object, the same is true. It either contains links to other objects or primitives directly. Objects are always links in any context, and these links are passed by value.

Thus, we can have:

 [ STACK ] [ HEAP ] int a: 10; -> MyWrapperObject@21f03b70 ====|| double b: 10.4; | || int someField: 11 || MyWrapperObject@21f03b70 ------| || String@10112222 ---------- ...... ||==========================|| | | | String@10112222 ============||<---- || ... || || ... || }}=========================|| 

Note that the use in some cases (for example, inside internal JVM objects) of objects can be stored in memory without a heap.

+17
source

In general, local variables are stored on the stack. Instance variables are stored on the heap.

+2
source

Java works the same way. Keep in mind that no variable in Java has an object as a value; all object variables (and the field) are references to objects. The objects themselves are supported somewhere (usually on the heap) by the Java virtual machine. Java has automatic garbage collection, so (unlike C) you don't have to worry about freeing an object. When all live links to it go beyond, it will eventually be noticed by the garbage collector.

For instance:

 Dog myDog = new Dog(); someMethod(myDog); 

passes someMethod reference to the dog object referenced by myDog . Changes to the object that may occur inside someMethod will be displayed in myDog after the method returns.

+1
source

It works similarly. In fact, what happens is that the object itself is stored on the heap, and the reference to the object, which is similar to the C pointer, is stored in a local variable.

0
source

This is exactly the same as the C pointer, and almost always on the stack. In C, the object itself is on the heap when you say new Dog(); , but the Dog * myDogP (4 or 8 bytes) does not have to be on the heap and is usually on the stack.

0
source

All references to s1, s2, ob1, obj2 and obj3 will be stored in Stack .

Object data will be stored on the Heap (and for String, for example, can be stored in a special pool of constants).

enter image description here

0
source

Source: https://habr.com/ru/post/956833/


All Articles