Junior
What is heap and stack?
sobes.tech AI
Answer from AI
Heap and Stack are two memory areas used by programs to store data.
-
Stack — this is a memory area where local variables, function parameters, and return addresses are stored. It operates on a LIFO (Last In, First Out) principle. When a function is called, a block is allocated on the stack for it, and after it finishes, it is freed. The stack has a limited size and is managed automatically.
-
Heap — this is a memory area for dynamic allocation of objects and data, whose size can change during program execution. In Java, objects are created in the heap, and the garbage collector automatically frees unused memory.
Example:
public void example() {
int a = 10; // stored in the stack
String s = new String("Hello"); // String object is created in the heap
}
Here, a is a local variable in the stack, and the String object is in the heap.