-
Notifications
You must be signed in to change notification settings - Fork 137
stack memory
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.
Every method call creates a new stack frame.
Example:
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:
quantity = 2
price = 150.00
total = 300.00
When the method finishes, the stack frame is removed.
Example:
public void processBill() {
calculateTotal();
}
public void calculateTotal() {
double total = 500.00;
}Stack order:
processBill()
calculateTotal()
The most recently called method is removed first.
This is called:
Last In, First Out
or:
LIFO
Local variables are normally stored inside the current method's stack frame.
Example:
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.
A local reference variable is stored in stack memory.
The actual object is stored in heap memory.
Example:
public void createPatient() {
Patient patient = new Patient();
}Memory idea:
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 are stored in the method's stack frame.
Example:
public double calculateNetTotal(
double total,
double discount) {
return total - discount;
}The parameters total and discount are available only while the method is running.
Primitive local variables are stored directly in the stack frame.
Example:
public void calculate() {
int quantity = 5;
double price = 200.00;
boolean valid = true;
}The values are stored directly:
quantity = 5
price = 200.00
valid = true
public void processReport() {
int recordCount = 20;
String reportName = "Patient Report";
Department department = new Department();
}Memory idea:
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 memory is limited.
A StackOverflowError may occur when methods call themselves continuously.
Example:
public void repeat() {
repeat();
}This method never stops calling itself.
Each call creates a new stack frame.
Eventually, the stack becomes full.
Result:
java.lang.StackOverflowError
Correct recursion must have a stopping condition.
public void countDown(int number) {
if (number <= 0) {
return;
}
countDown(number - 1);
}Each thread has its own stack.
Example:
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.
A static member belongs to the class.
Example:
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.
public static boolean isValidAmount(double amount) {
return amount > 0;
}Call:
AmountValidator.isValidAmount(100.00);When the static method runs, its local variables and parameters are still stored in a stack frame.
Example:
public static boolean isValidAmount(double amount) {
boolean valid = amount > 0;
return valid;
}Here:
-
amountis in the method stack frame. -
validis in the method stack frame. - The method is static, but its local execution data still uses stack memory.
A non-static member belongs to an object.
Example:
private String patientName;Each object has its own patientName value.
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:
public String formatPatientName() {
String formattedName = patientName.trim();
return formattedName;
}Here:
-
patientNamebelongs to the object in heap memory. -
formattedNameis a local variable in stack memory. - The current object reference, called
this, is available in the stack frame.
| 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 |
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:
Stack during generateReport():
resultCount = 25
this reference
Heap:
PatientReport object
reportName
department
Shared static data:
generatedReportCount
- Each thread has its own stack.
- Every method call creates a stack frame.
- Local variables are stored in the stack frame.
- Method parameters are stored in the stack frame.
- Local object variables store references in the stack.
- Actual objects are stored in heap memory.
- Stack data is removed when the method finishes.
- Static methods still use stack frames when they execute.
- Non-static attributes belong to objects in heap memory.
- Infinite recursion can cause
StackOverflowError.
Stack memory is mainly used for method execution.
It stores:
Method calls
Local variables
Parameters
Primitive local values
Object references
Example:
public void process() {
int count = 10;
Patient patient = new Patient();
}Memory idea:
Stack:
count = 10
patient reference
Heap:
Patient object