Stack memory

1) Stack memory is used to store local variables and references to other objects in the method whereas heap memory is used to store objects.
2) Size of heap memory is much bigger than the stack memory.
3) Each thread has their own stack which stores local variables and these variables are not accessible globally whereas objects stored in heap are globally accessible.
4) Heap memory size is bigger where we can create and store objects in any order whereas stack memory follows LIFO(Last In First Out) order.
5) We can change the size of heap memory using jvm parameters : -Xms for initial heap memory and –Xmx for maximum heap memory. For stack , use –Xss to specify stack size for each thread.
6) If stack memory is filled up then you will get java.lang.StackOverFlowError . If there is no space left to allocate new Object in Heap memory then you will get java.lang.OutOfMemoryError: Java Heap Space.

Program to generate StackOverFlowError exception :

Java

1

2

3

4

5

6

7

8

9

10

11

12

13

14

packagecom.j2eereference;

publicclassStackOverflowErrorDemo{

publicstaticvoidrecursiveComputation(intcount)

{

if(count==0)

return;

else

recursiveComputation(++count);

}

publicstaticvoidmain(String[]args)

{

StackOverflowErrorDemo.recursiveComputation(10);

}

}

OutPut:
Exception in thread “main” java.lang.StackOverflowError
at com.j2eereference.StackOverflowErrorDemo.recursiveComputation(StackOverflowErrorDemo.java:13)
at com.j2eereference.StackOverflowErrorDemo.recursiveComputation(StackOverflowErrorDemo.java:13)

Program to generate OutOfMemoryError: Java heap space

Java

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

packagecom.j2eereference;

importjava.util.ArrayList;

importjava.util.List;

publicclassOutOfMemoryDemo

{

privatestaticList<String>heapList=newArrayList<>();

publicstaticvoidmain(String[]args)

{

while(true)

{

heapList.add(newString("Shobhna"));

}

}

}

OutPut:
Exception in thread “main” java.lang.OutOfMemoryError: Java heap space
at java.util.Arrays.copyOf(Arrays.java:3210)
at java.util.Arrays.copyOf(Arrays.java:3181)
at java.util.ArrayList.grow(ArrayList.java:261)
at java.util.ArrayList.ensureExplicitCapacity(ArrayList.java:235)
at java.util.ArrayList.ensureCapacityInternal(ArrayList.java:227)
at java.util.ArrayList.add(ArrayList.java:458)
at com.j2eereference

7) Stack memory allocation is simple as compared to heap memory allocation as Stack uses LIFO order,so stack memory is fast as compared to heap memory.
8) Stack memory is used by only threads whereas heap memory is used by whole application.
9) use stack when you know that how much memory is needed to allocate before compile time on the other hand, use heap if you are not sure about the amount of memory needed at runtime.