Storing objects on the heap
Storing objects on the heap is very different from storing values on the stack. As we’ve just seen, references to places on the heap are stored on the stack. These references are memory addresses and these memory addresses translate to a certain place on the heap where the object is being stored. Without this object reference, we would have no way to access an object on the heap.
Object references have a certain type. There are very many built-in types in Java that we can use, such as ArrayList
, String
, all the wrapper classes, and more, but we can also create our own objects and these objects will be stored on the heap too.
The heap memory holds all the objects that exist in the application. Objects on the heap can be accessed from everywhere in the application using the address of the object, the object reference. The objects contain the same things as the blocks on the stack: the primitive values directly and the addresses for other objects...