Java/J2EE and SOA (348 Blogs) Become a Certified Professional
AWS Global Infrastructure

Programming & Frameworks

Topics Covered
  • C Programming and Data Structures (16 Blogs)
  • Comprehensive Java Course (4 Blogs)
  • Java/J2EE and SOA (345 Blogs)
  • Spring Framework (8 Blogs)
SEE MORE

What is Memory Allocation in Java? Stack and Heap Memory

Last updated on Jun 17,2021 8.2K Views


Memory allocation is a process by which computer programs and services are assigned with physical or virtual memory space. In this article, we shall learn about memory allocation in Java and we will discuss Stack and Heap Memory.

 

What is Stack Memory?

Java Stack memory is used for the execution of a thread. They contain method-specific values that are short-lived and references to other objects in the heap that is getting referred from the method.

Stack memory is always referenced in LIFO (Last-In-First-Out) order. Whenever a method is invoked, a new block is created in the stack memory for the method to hold local primitive values and reference to other objects in the method.

As soon as the method ends, the block becomes unused and becomes available for the next method.

Stack memory size is very less compared to Heap memory.

 

Key Features of Stack Memory

Apart from what we have discussed so far, following are some other features of Stack memory:

  • It grows and shrinks as new methods are called and returned respectively
  • Variables inside stack exist only as long as the method that created them is running
  • It’s automatically allocated and deallocated when method finishes execution
  • If this memory is full, Java throws java.lang.StackOverFlowError
  • Access to this memory is fast when compared to heap memory
  • This memory is thread-safe as each thread operates in its own stack

 

Methods in Stack class

  • Object push(Object element): Pushes an element on the top of the stack.
  • Object pop(): Removes and returns the top element of the stack. An ‘EmptyStackException’ exception is thrown if we call pop() when the invoking stack is empty.
  • Object peek(): Returns the element on the top of the stack, but does not remove it.
  • Boolean empty(): It returns true if nothing is on the top of the stack. Else, returns false.
  • int search(Object element): It determines whether an object exists in the stack. If the element is found, it returns the position of the element from the top of the stack. Else, it returns -1.

 

Java code for stack implementation

import java.io.*;
import java.util.*;

class Test{
      static void stack_push(Stack<Integer> stack){
             for(int i = 0; i < 5; i++){
                    stack.push(i);
             }
      }
      static void stack_pop(Stack<Integer> stack){
      System.out.println("Pop :");
      for(int i = 0; i < 5; i++){
            Integer y = (Integer) stack.pop();
            System.out.println(y);
      }
}
static void stack_peek(Stack<Integer> stack){
      Integer element = (Integer) stack.peek();
      System.out.println("Element on stack top : " + element);
}
static void stack_search(Stack<Integer> stack, int element){
      Integer pos = (Integer) stack.search(element);
      if(pos == -1)
            System.out.println("Element not found");
      else
            System.out.println("Element is found at position " + pos);
      }
     public static void main (String[] args){
           Stack<Integer> stack = new Stack<Integer>();
           stack_push(stack);
           stack_pop(stack);
           stack_push(stack);
           stack_peek(stack);
           stack_search(stack, 2);
           stack_search(stack, 6);
     }
}

//Output

memory-allocation-in-java

Now, Let us move into Heap Space.

 

Heap Space in Java

The memory is allocated during the execution of instructions written by programmers. Note that the name heap has nothing to do with heap data structure. It is called heap because it is a pile of memory space available to programmers to allocated and de-allocate. If a programmer does not handle this memory well, a memory leak can happen in the program.

 

Key Features of Java Heap Memory

  • Apart from what we have discussed so far, following are some other features of heap space:
  • It’s accessed via complex memory management techniques that include Young Generation, Old or Tenured Generation, and Permanent Generation
  • If heap space is full, Java throws java.lang.OutOfMemoryError
  • Access to this memory is relatively slower than stack memory
  • This memory, in contrast to stack, isn’t automatically deallocated. It needs Garbage Collector to free up unused objects so as to keep the efficiency of the memory usage
  • Unlike stack, a heap isn’t thread-safe and needs to be guarded by properly synchronizing the code

 

Difference between Java Heap Space and Stack Memory

Based on the above explanations, we can easily conclude the following differences between Heap and Stack memory.

  • Heap memory is used by all the parts of the application whereas stack memory is used only by one thread of execution.
  • Whenever an object is created, it’s always stored in the Heap space and stack memory contains the reference to it. Stack memory only contains local primitive variables and reference variables to objects in heap space.
  • Objects stored in the heap are globally accessible whereas stack memory can’t be accessed by other threads.
  • Memory management in the stack is done in a LIFO manner whereas it’s more complex in Heap memory because it’s used globally. Heap memory is divided into Young-Generation, Old-Generation etc, more details at Java Garbage Collection.
  • Stack memory is short-lived whereas heap memory lives from the start till the end of application execution.
  • We can use -XMX and -XMS JVM option to define the startup size and maximum size of heap memory. We can use -XSS to define the stack memory size.
  • When stack memory is full, Java runtime throws java.lang.StackOverFlowError whereas if heap memory is full, it throws java.lang.OutOfMemoryError: Java Heap Space error.
  • Stack memory size is very less when compared to Heap memory. Because of simplicity in memory allocation (LIFO), stack memory is very fast when compared to heap memory.

 

Comparison Chart

PARAMETERSTACKHEAP
Basic Memory is allocated in a Contiguous BlockMemory is allocated in a Random Order
 Allocation and Deallocation Automatic by compilerManual by Programmer
 CostLessMore
 ImplementationHardEasy
 Access timeFaster Slower
 Main Issue Shortage of Memory Memory Fragmentation
 Locality of DifferenceExcellent Adequate
 FlexibilityFixed-Rate Resizing is possible

 

With this, we come to an end of this “Memory Allocation in Java” Tutorial. I hope you have understood the concept and its implementation through some real-time examples.

Now that you have understood Memory Allocation in Java basics through this “Memory Allocation in Java” article check out the Java Online Training by Edureka, a trusted online learning company with a network of more than 250,000 satisfied learners spread across the globe. Edureka’s Java J2EE and SOA training and certification courses are designed for students and professionals who want to be a Java Developer. The course is designed to give you a head start into Java programming and train you for both core and advanced Java concepts along with various Java frameworks like Hibernate & Spring.

Got a question for us? Mention it in the comments section of this “Memory Allocation in Java” blog and we will get back to you as soon as possible.

Upcoming Batches For Java Certification Training Course
Course NameDateDetails
Java Certification Training Course

Class Starts on 27th April,2024

27th April

SAT&SUN (Weekend Batch)
View Details
Java Certification Training Course

Class Starts on 18th May,2024

18th May

SAT&SUN (Weekend Batch)
View Details
Comments
0 Comments

Join the discussion

Browse Categories

webinar REGISTER FOR FREE WEBINAR
REGISTER NOW
webinar_success Thank you for registering Join Edureka Meetup community for 100+ Free Webinars each month JOIN MEETUP GROUP

Subscribe to our Newsletter, and get personalized recommendations.

image not found!
image not found!

What is Memory Allocation in Java? Stack and Heap Memory

edureka.co