Sobes.tech
Middle

Where are objects stored in memory?

sobes.tech AI

Answer from AI

In Java/JVM, objects are stored in a dynamic memory area — the heap. Primitive data types (int, boolean, char, etc.) and references to objects are stored in the stack when declared as local variables within methods.

Briefly:

  • Objects: Heap.
  • Primitive types and object references as local variables: Stack.

Example placement:

// Local variable of primitive type - stored in the stack
int count = 10;

// Local variable-reference to an object - stored in the stack
// The String object "Hello" itself is created in the heap
String message = new String("Hello");

// Local variable-reference to an object - also in the stack
// The StringBuilder object is created in the heap
StringBuilder builder = new StringBuilder();

// Accessing the object through the reference from the stack
builder.append("World");

More details:

Memory Area What is stored Lifetime
Heap All created objects, arrays. Determined by the garbage collector, when there are no active references to the object.
Stack Local variables, method parameters, call information. Determined by the method's lifetime. Freed upon method completion.
PermGen (before Java 8) / Metaspace (from Java 8) Class metadata, class information, interned strings (for PermGen). Depends on JVM and used classes.
Code Cache Compiled machine code (generated by HotSpot JIT compiler). Depends on JVM.

It is important to note that strings can have special behavior. The String Pool (String Pool) is located in the heap (or PermGen/Metaspace depending on Java version) and stores interned strings, which helps save memory when using the same string literals multiple times.