# Java Stack Memory ## Introduction Stack memory is used when Java methods are called. Each thread has its own stack. The stack stores: - Method calls - Local variables - Method parameters - Primitive local values - References to objects stored in heap memory Stack memory is temporary. When a method finishes, its stack frame is removed automatically. --- ## Stack Frame Every method call creates a new stack frame. Example: ```java public void calculateTotal() { int quantity = 2; double price = 150.00; double total = quantity * price; } ``` When `calculateTotal()` runs, a stack frame is created. The stack frame contains: ```text quantity = 2 price = 150.00 total = 300.00 ``` When the method finishes, the stack frame is removed. --- ## Method Calls in Stack Memory Example: ```java public void processBill() { calculateTotal(); } public void calculateTotal() { double total = 500.00; } ``` Stack order: ```text processBill() calculateTotal() ``` The most recently called method is removed first. This is called: ```text Last In, First Out ``` or: ```text LIFO ``` --- ## Local Variables Local variables are normally stored inside the current method's stack frame. Example: ```java public void processPatient() { int patientCount = 10; boolean active = true; } ``` The variables `patientCount` and `active` exist only while `processPatient()` is running. They cannot be used after the method finishes. --- ## Object References in Stack Memory A local reference variable is stored in stack memory. The actual object is stored in heap memory. Example: ```java public void createPatient() { Patient patient = new Patient(); } ``` Memory idea: ```text Stack: patient reference | v Heap: Patient object ``` The variable `patient` is in the stack frame. The `Patient` object created with `new Patient()` is in heap memory. --- ## Method Parameters Method parameters are stored in the method's stack frame. Example: ```java public double calculateNetTotal( double total, double discount) { return total - discount; } ``` The parameters `total` and `discount` are available only while the method is running. --- ## Primitive Values in Stack Memory Primitive local variables are stored directly in the stack frame. Example: ```java public void calculate() { int quantity = 5; double price = 200.00; boolean valid = true; } ``` The values are stored directly: ```text quantity = 5 price = 200.00 valid = true ``` --- ## Stack Memory Example ```java public void processReport() { int recordCount = 20; String reportName = "Patient Report"; Department department = new Department(); } ``` Memory idea: ```text Stack: recordCount = 20 reportName reference department reference Heap: "Patient Report" object Department object ``` The local primitive `recordCount` is stored in the stack. The local variables `reportName` and `department` store references. Their objects are stored in heap memory. --- ## Stack Overflow Error Stack memory is limited. A `StackOverflowError` may occur when methods call themselves continuously. Example: ```java public void repeat() { repeat(); } ``` This method never stops calling itself. Each call creates a new stack frame. Eventually, the stack becomes full. Result: ```text java.lang.StackOverflowError ``` Correct recursion must have a stopping condition. ```java public void countDown(int number) { if (number <= 0) { return; } countDown(number - 1); } ``` --- ## Stack Memory and Threads Each thread has its own stack. Example: ```text Thread 1 → Stack 1 Thread 2 → Stack 2 Thread 3 → Stack 3 ``` Local variables in one thread's stack are not directly shared with another thread. However, stack references may point to the same object in heap memory. --- ## Static and Non-Static Difference ### Static Members A static member belongs to the class. Example: ```java private static int patientCount; ``` There is only one shared `patientCount` value for the class. A static variable is not a local stack variable. It is associated with the loaded class and is shared by all objects. A static method can be called without creating an object. ```java public static boolean isValidAmount(double amount) { return amount > 0; } ``` Call: ```java AmountValidator.isValidAmount(100.00); ``` When the static method runs, its local variables and parameters are still stored in a stack frame. Example: ```java public static boolean isValidAmount(double amount) { boolean valid = amount > 0; return valid; } ``` Here: - `amount` is in the method stack frame. - `valid` is in the method stack frame. - The method is static, but its local execution data still uses stack memory. ### Non-Static Members A non-static member belongs to an object. Example: ```java private String patientName; ``` Each object has its own `patientName` value. ```java Patient firstPatient = new Patient(); Patient secondPatient = new Patient(); ``` The two objects can store different names. Non-static attributes are stored as part of their objects in heap memory. When a non-static method runs, its local variables and parameters use stack memory. Example: ```java public String formatPatientName() { String formattedName = patientName.trim(); return formattedName; } ``` Here: - `patientName` belongs to the object in heap memory. - `formattedName` is a local variable in stack memory. - The current object reference, called `this`, is available in the stack frame. --- ## Static vs Non-Static Summary | Feature | Static | Non-static | |---|---|---| | Belongs to | Class | Object | | Number of copies | One shared copy | One copy per object | | Object required | No | Yes | | Can access instance fields directly | No | Yes | | Local variables during method call | Stack | Stack | | Attribute storage | Shared class-associated storage | Inside object in heap | --- ## HMIS-Style Example ```java public class PatientReport { private static int generatedReportCount; private String reportName; private Department department; public void generateReport() { int resultCount = 25; generatedReportCount++; System.out.println(reportName); System.out.println(resultCount); } public static int getGeneratedReportCount() { return generatedReportCount; } } ``` Memory idea: ```text Stack during generateReport(): resultCount = 25 this reference Heap: PatientReport object reportName department Shared static data: generatedReportCount ``` --- ## Important Points 1. Each thread has its own stack. 2. Every method call creates a stack frame. 3. Local variables are stored in the stack frame. 4. Method parameters are stored in the stack frame. 5. Local object variables store references in the stack. 6. Actual objects are stored in heap memory. 7. Stack data is removed when the method finishes. 8. Static methods still use stack frames when they execute. 9. Non-static attributes belong to objects in heap memory. 10. Infinite recursion can cause `StackOverflowError`. --- ## Summary Stack memory is mainly used for method execution. It stores: ```text Method calls Local variables Parameters Primitive local values Object references ``` Example: ```java public void process() { int count = 10; Patient patient = new Patient(); } ``` Memory idea: ```text Stack: count = 10 patient reference Heap: Patient object ```