Java Memory Model
- Java variables do not contain the actual objects, they contain references to the objects.
- The actual objects are stored in an area of memory known as the heap.
- Local variables referencing those objects are stored on the stack.
- More than one variable can hold a reference to the same object.
Figure 1. Java Memory Model
As previously mentioned, the stack is the area of memory where local variables (including method parameters) are stored. When it comes to object variables, these are merely references (pointers) to the actual objects on the heap.
Every time an object is instantiated, a chunk of heap memory is set aside to hold the data (state) of that object. Since objects can contain other objects, some of this data can in fact hold references to those nested objects.
In Java:
-
Object references can either point to an actual object of a compatible type, or be set to
null
(0
is not the same asnull
). - It is not possible to instantiate objects on the stack. Only local variables (primitives and object references) can live on the stack, and everything else is stored on the heap, including classes and static data.
No comments:
Post a Comment