What is the difference between stack and heap memory in Java?

PointStackHeap
KeepsMethod calls, local variables, referencesObjects and arrays
PerOne stack for each threadOne heap shared by all threads
CleanedWhen the method endsBy the garbage collector
SizeSmallBig
Error when fullStackOverflowErrorOutOfMemoryError
public class Main {
    static void recurse(int n) {
        recurse(n + 1);
    }

    public static void main(String[] args) {
        int local = 5;                               // on the stack
        String s = new String("object");            // the object is on the heap, the reference s on the stack

        try {
            recurse(1);
        } catch (StackOverflowError e) {
            System.out.println("Stack is full: StackOverflowError");
        }
        System.out.println(local + " " + s);
    }
}
Output

Stack is full: StackOverflowError
5 object

Size options: -Xss for the stack and -Xmx for the maximum heap. See Java Recursion.


Learn more about the similar topics:
Tutorials
No Content Found.
Exercises & Assignments
No Content Found.
Interview Questions & Answers
No Content Found.