Sobes.tech
Junior

Kus mälus hoituvad objektid?

sobes.tech AI

Vastus AI-lt

Objects in memory are stored in the heap.

The heap is a dynamically allocated area of memory where objects are placed during program execution. The size of objects is not known in advance, and they are removed by the garbage collector.

Primitive data types (integers, boolean values, etc.) are usually stored in the stack. The stack is a statically allocated area of memory used for storing local variables and function call information, and it is managed automatically.

References to objects (i.e., addresses in the heap) are stored either on the stack or within other objects in the heap.

Example in Java:

// A primitive type variable (int) is stored on the stack.
int count = 10;

// A reference variable (myObject) is stored on the stack.
// The MyObject object itself is created in the heap.
MyObject myObject = new MyObject();

// A primitive type inside the object (id) is stored as part of the object in the heap.
myObject.setId(1);

// A reference to another object (anotherObject) inside myObject
// is stored as part of myObject in the heap. The AnotherObject itself is in the heap.
myObject.setRelatedObject(new AnotherObject());

class MyObject {
    private int id; // stored in the heap (as part of MyObject)
    private AnotherObject relatedObject; // reference stored in the heap

    public void setId(int id) {
        this.id = id;
    }

    public void setRelatedObject(AnotherObject relatedObject) {
        this.relatedObject = relatedObject;
    }
}

class AnotherObject {
    // ...
}

Thus:

  • Stack: Primitive types, references to objects.
  • Heap: The objects themselves, containing their fields (including primitive types inside objects and references to other objects).