How does Java\'s reference variable stored? Is that work similar to C pointer?
what I mean by reference variable is myDog in this code
Dog myDog = ne
In general local variables are stored on the stack. Instance variables are stored on the heap.
It does work similarly. What is actually happening is that the object itself is stored in the heap, and a reference to the object, which is just like a C pointer, is stored in a local variable.
Java works the same way. Be aware that no variable in Java has an object as a value; all object variables (and field) are references to objects. The objects themselves are maintained somewhere (usually on the heap) by the Java virtual machine. Java has automatic garbage collection, so (unlike in C) you don't need to worry about freeing the object. Once all live references to it are out of scope, it will eventually be swept up by the garbage collector.
For instance:
Dog myDog = new Dog();
someMethod(myDog);
passes to someMethod
a reference to the dog object that is referenced by myDog
. Changes to the object that might occur inside someMethod
will be seen in myDog
after the method returns.
It is exactly the same as a 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
pointer (4 or 8 bytes) need not be on the heap and is usually on the stack.
You need to understand a bit of the lower levels of Java memory organization. On the stack, primitives(int, double, boolean, etc) and object references pointing to the heap are stored.
Inside any object the same is true. It either contains references to other objects or primitives directly. Objects are always references in any context and those references are passed by value.
So we may have:
[ STACK ] [ HEAP ]
int a: 10; -> MyWrapperObject@21f03b70====||
double b: 10.4; | || int someField: 11 ||
MyWrapperObject@21f03b70 ------| || String@10112222 ----------
...... ||==========================|| |
|
|
String@10112222============||<----
|| ... ||
|| ... ||
}}=========================||
Note that use in some cases(as in via JVM internals) objects may be stored in non-heap memory.
All the references to s1, s2, ob1, obj2 and obj3 will be stored in the Stack.
The objects data, will be stored in the Heap (and for String for example in can be stored in a special constant pool).