Delving into the object life cycle
To understand Java, it is extremely helpful to have an appreciation of what is happening in the background, in memory. This section will help cement what is happening on the stack and the heap when we call methods, declare local/instance variables, and so forth.
Local variables are kept on the stack (for fast access), whereas instance variables and objects live on the heap (a large area of memory). As we know, we use the new
keyword to create a Java object. The new
keyword allocates space on the heap for the object and returns the reference to the object. What happens if the object is no longer accessible? For example, the reference may have gone out of scope. How do we reclaim that memory? This is where garbage collection comes into play.
Garbage collection
As mentioned previously, garbage collection reclaims memory taken up by objects that are no longer being used; as in the objects have no references pointing to them. This garbage collection...