What is the difference between stack and heap memory in Java?
| Point | Stack | Heap |
|---|---|---|
| Keeps | Method calls, local variables, references | Objects and arrays |
| Per | One stack for each thread | One heap shared by all threads |
| Cleaned | When the method ends | By the garbage collector |
| Size | Small | Big |
| Error when full | StackOverflowError | OutOfMemoryError |
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. |