Now, this is not an in depth explanation of References, but is a good introductory/overview of Java References.
In C/C++, you had pointers. You’d create an object and point to its location in memory, and it was great when you had limitations and different segments of memory to work with.
However, you had to keep track of pointers, you didn’t get to define where pointers were, and you had to clean up after yourself. So while it made some things easier/better, it also made things a lot worse, or should I say complicated.
References takes the same idea, except, instead of making you the programmer responsible for creating and removing the memory, the JVM is responsible for it.
When you create an object, you create a location in memory, and a reference to that location. It’s like a pointer, but the JVM has control over it.
SampleClass obj = new SampleClass(); // memory is allocated for our object, and then referenced
As long as this object is in scope, and not destroyed, the memory is there and can be used by referencing the object. But what if we “destroy” it.
Well, Java doesn’t have commands like the free
and delete
commands in C/C++. Instead, you set an object to null
. It will no longer reference that chunk of memory.
obj = null; // now you cannot use obj
The JVM will also keep track of when an object goes out of scope, and automatically free up that memory. No more having to remember to delete
/free
an object or child object, reducing the chances of memory leaks.
The JVM and References
Now references might seem just like simpler pointers, and to the casual programmer it is. However, to the JVM, there is more that is going on “under the hood”.
The JVM has to keep track of which objects are still visible, and it will mark any that have fallen out of scope, or set to null
, to be marked for deletion. However, that memory, while no longer accessible, is not necessarily deleted right away.
Instead the JVM just marks it for deletion and keeps on working. Periodically the JVM will do something called garbage collection. Here it removes the objects from memory, creating free spaces to add new objects. This is an “expensive” process so the JVM doesn’t do it very often, unless the free space for the application is running low.
The JVM, because it is keeping track of all of the objects and where the references point to, may also move items around in memory, freeing up larger contiguous spaces in memory if necessary. For example, if it needs to create a large array.
References to Objects in Java was originally found on Access 2 Learn