Junior
Where are reference data types stored?
sobes.tech AI
Answer from AI
Reference data types are stored:
- In the Heap: The objects themselves. The heap is a region of memory allocated during program execution where all dynamically created objects reside.
- In the Stack: References (pointers) to these objects. The stack is a region of memory used for storing local variables, method parameters, and call information. Each reference in the stack contains the address of the object in the heap.
Example:
// String object "Hello" is stored in the heap (or in the string pool)
String str = new String("Hello");
// The variable str is stored in the stack and contains a reference to the String object
int[] numbers = new int[10]; // The array is stored in the heap
// The variable numbers is stored in the stack and holds a reference to the array
- In the String Pool: Some string literals. The string pool is a special area in the heap where unique string literals are stored to optimize memory usage.
String s1 = "World"; // The literal "World" can be placed in the string pool
String s2 = "World"; // s2 will refer to the same string in the pool as s1