Stack memory and Heap memory are the two important components of JVM. Whenever a program execution starts JVM allocates memory to all the class, object, methods, variables.
Basically used for thread execution. It works in LIFO (Last in First Out) manner. As soon as any method encountered JVM allocates memory to the primitive variables in the Stack Memory.
For the non-primitive variables like string or object, JVM allocates memory in Heap but the reference of that remains in the Stack memory for execution.
As soon as the method ends, memory de-allocated and ready for the next method. The size of the Stack is less than the Heap memory.
Heap memory is bigger than the Stack memory. It loads all the Runtime classes into the heap when we execute the program. All the objects and array would be allocated memory in the heap and available until the program execution completed.
Comparison between Stack and Heap
|Stack Memory||Heap Memory|
|Contains only local primitive variables.||Contains objects and non-primitive variables.|
|Available for current thread.||Available for the entire program.|
|Stack works in LIFO manner.||There is no such restriction.|
|It throws StackOverFlowError when gets full.||It throws OutOfMemoryError when gets full.|
|Size of Stack memory is less and faster than Heap.||Size of Heap big than Stack and depends on the OS configuration.|
- Basic Java – 1 || Understand Java before start learning JAVA.
- Basic Java – 2 || Variables and Data Types used in JAVA.
- Basic Java – 3 || Understanding Class, Objects, Methods in Java.
- Basic Java – 4 || More on methods(Return Type and Parameters)
- Basic Java – 5 || Methods- Call by Value and Call by Reference in Java.
- Basic Java – 6 || Understanding of Constructor and Destructor in JAVA.
- Basic Java – 7 || Static Variables and Methods.
- Basic Java – 8 || Lets learn about Arrays in Java.
- Basic Java – 9 || Performing multiple operations using Java Operators.
- Basic Java – 10 || Conditions (If and Switch) in JAVA.
- Basic Java – 11 || for and for-each in Java. (Loops Part-1)
- Basic Java – 12 || Alternate looping concepts while and do-while. (Loops Part-2)
- Basic Java – 13 || Decimal values v/s Octal base(8) values in JAVA.
- Basic Java – 14 || Learn about String literals in Java.
- Basic Java – 15 || Runtime User Input using Scanner Class (Part-1).
- Basic Java – 16 || Runtime User Input using BufferedReader Class (Part-2).
- Basic Java – 17 || Runtime User Input using Console Class (Part-3).
- Basic Java – 18 || Difference between break and continue keywords.
- Basic Java – 19 || Sending Email using Java (Part-1).
- Basic Java – 20 || Sending Email with attachment using Java (Part-2).
- Basic Java – 21 || Stack memory and Heap memory in Java.
- Basic Java – 22 || Let’s learn more about String.