Junior
Where are objects stored in Java?
sobes.tech AI
Answer from AI
Objects in Java are stored:
- In the Heap: Most objects are created in the heap. This is dynamically allocated memory accessible to all threads of the application. The garbage collector manages heap memory by freeing unused objects.
- In the Stack: Primitive data types (int, boolean, etc.) and references to objects are stored in the stack. The stack is managed by the thread of execution, and data is automatically removed when it goes out of scope.
- In the Method Area: Contains class metadata (class structure, method names, variables, etc.), static variables, and String constant pools.
Sometimes objects can be fully optimized by the compiler and may not exist explicitly in memory (e.g., escape analysis).
// Example: object in heap, reference in stack
Object myObject = new Object(); // myObject - reference in stack, new Object() - object in heap
// Example: primitive type in stack
int myInt = 5; // myInt - primitive type in stack
// Example: static variable in method area
public class MyClass {
static String staticField = "Hello"; // staticField - in method area (String Pool)
}