What is the difference between stack memory and heap memory in Java?
Java keeps two kinds of memory apart, and the difference between them decides where your data lives and how it is cleaned up.
The stack holds the things that belong to a running method. Every time a method is called, Java sets aside a stack frame for it. That frame holds the method's local variables, the values it is working on, and the information needed to come back to the code that called it. When the method returns, the frame is thrown away and the space is ready for the next call. The stack grows and shrinks automatically as methods are called and return.
The heap holds the objects. Every object you create with new lives on the heap, along with its fields. The heap is not cleaned up by the end of a method. It is cleaned up by the garbage collector, which looks for objects that nothing can reach any more and frees them.
There are two more facts that make this easier to picture. Each thread has its own stack, so one thread cannot walk into another thread's frames. The heap is shared by all of the threads, which is why two threads can work on the same object, and why you have to be careful when they do.
public class Main {
static int staticCounter = 1; // lives with the class, not in a stack frame
public static void main(String[] args) {
int local = 42; // lives in the stack frame of main
Object thing = new Object(); // the object lives on the heap
System.out.println("local : " + local);
System.out.println("heap : " + thing);
}
}
The next question in this topic looks at exactly where each piece of your data ends up.