Friday, March 8, 2024

Java Heap & Stack

In Java, objects are typically allocated memory in the heap. Let's break down the examples provided earlier to understand where the variables are stored:

Class Scope (Static Variable)

   public class MyClass {

       public static int globalVariable = 42;

   }

   - The `globalVariable` is a class variable declared as `static`. It is associated with the class itself and stored in the heap. It exists for the entire lifetime of the program or until the class is unloaded.

Instance Scope (Instance Variable):

   public class MyClass {

       public int instanceVariable = 42;

   }

   - The `instanceVariable` is an instance variable. It is associated with instances of the class and stored in the heap. Each object created from this class will have its own copy of `instanceVariable`.

Method Scope (Local Variable):

   public class MyClass {

       public void myMethod() {

           int localVar = 42;

           // localVar is accessible only within myMethod

       }

   }

   - The `localVar` is a local variable declared within the `myMethod` method. Local variables are stored on the stack and have a scope limited to the method or block in which they are declared. Once the method completes execution, the memory for local variables is reclaimed.

- Class variables (`static`) and instance variables are stored in the heap.

- Local variables are stored on the stack, and their memory is reclaimed when the method or block in which they are declared exits.

Note that Java abstracts away the details of memory management from the developer, and the Java Virtual Machine (JVM) is responsible for memory allocation and garbage collection. 

The use of the heap and stack depends on the type of variable and its scope.

No comments:

Post a Comment

LeetCode C++ Cheat Sheet June

🎯 Core Patterns & Representative Questions 1. Arrays & Hashing Two Sum – hash map → O(n) Contains Duplicate , Product of A...