Sobes.tech
Senior

Is a primitive object field stored in the heap or in the stack?

sobes.tech AI

Answer from AI

In Java, primitive fields of an object are always stored inside the object, which resides in the heap.

Explanation:

  • Objects in Java are created in the heap.
  • All fields of an object (primitive and reference) are part of the object and are stored together with it in the heap.
  • Primitive fields occupy a fixed space within the object.

The stack is used to store local variables of methods, including references to objects, but not for storing the objects themselves or their fields.

Example:

class MyClass {
    int number; // primitive field
}

MyClass obj = new MyClass();

Here, obj is a reference stored in the stack (if it's a local variable), and the MyClass object with the number field is in the heap.

In summary: a primitive field of an object resides in the heap, inside the object.