Fundamentals 4 min read

Understanding Java Heap vs Stack: Memory Allocation, Performance, and Code Examples

This article explains the differences between Java's heap and stack memory areas, their advantages and disadvantages, and demonstrates how string objects are allocated and shared with clear code examples that illustrate memory usage and performance implications.

Programmer DD
Programmer DD
Programmer DD
Understanding Java Heap vs Stack: Memory Allocation, Performance, and Code Examples

Heap and stack are the two areas in Java's RAM where data is stored.

Heap

Java's heap is a runtime data area where class objects allocate space. These objects are created via new and destroyed by the garbage collector.

The heap's advantage is dynamic memory allocation at runtime, eliminating the need to specify size at compile time, but its access speed is slower due to dynamic allocation.

Stack

The stack mainly stores primitive type variables (byte, short, int, long, float, double, boolean, char) and object references.

The stack's advantage is faster access and data sharing, but its size must be determined at compile time, lacking flexibility.

Example: Stack data can be shared

String can be created in two ways:

String str1 = new String("abc");<br/>String str2 = "abc";

The first creates a new object on the heap each time.

The second creates a reference in the stack; if the literal "abc" already exists in the string pool, the reference points to that existing object, otherwise it is added.

Code illustrating the theory:

public static void main(String[] args) {
    String str1 = new String("abc");
    String str2 = new String("abc");
    System.out.println(str1 == str2);
}

Output: false

public static void main(String[] args) {
    String str1 = "abc";
    String str2 = "abc";
    System.out.println(str1 == str2);
}

Output: true

Thus, using the second method creates only one object in memory, saving space and potentially improving performance because the JVM reuses the existing string from the pool.

Original Source

Signed-in readers can open the original source through BestHub's protected redirect.

Sign in to view source
Republication Notice

This article has been distilled and summarized from source material, then republished for learning and reference. If you believe it infringes your rights, please contactadmin@besthub.devand we will review it promptly.

JavaMemory ManagementGarbage CollectionStackHeapString Interning
Programmer DD
Written by

Programmer DD

A tinkering programmer and author of "Spring Cloud Microservices in Action"

0 followers
Reader feedback

How this landed with the community

Sign in to like

Rate this article

Was this worth your time?

Sign in to rate
Discussion

0 Comments

Thoughtful readers leave field notes, pushback, and hard-won operational detail here.