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