What is Memory Allocation in Java? Stack and Heap Memory

Last updated on Jun 17,2021 8.3K Views

What is Memory Allocation in Java? Stack and Heap Memory

edureka.co

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:

 

Methods in Stack class

 

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

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

 

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.

 

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 4th May,2024

4th May

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

Class Starts on 25th May,2024

25th May

SAT&SUN (Weekend Batch)
View Details
BROWSE COURSES
REGISTER FOR FREE WEBINAR UiPath Selectors Tutorial