Keep It Local: Understanding Local Variables in Java ⚙️
Definitions
Local variables are variables declared inside a
method, constructor, or block of code, accessible only within that scope.
Once the method finishes, these variables are removed.
![]() |
Local Variables and Memory Management in Java Stack vs Heap |
Code Example
public class LocalExample {
public static void main(String[] args) {
int totalMarks = 0; // Local variable declared inside the main method
totalMarks = 90 + 85 + 78;
System.out.println("The total marks are: " + totalMarks); // Output: The total marks are: 253
}
}
Methods and Memory Management in Java 🧠💾
Definitions
Stack Memory: Temporary storage for method calls and local variables.
Heap Memory: Long-term storage for objects created with new
.
Examples
Stack Memory Example
public class MemoryExample {
public static void main(String[] args) {
int number = 5; // Local variable stored in the stack
printNumber(number);
}
static void printNumber(int num) {
System.out.println("The number is: " + num);
}
}
Heap Memory Example
![]() |
Local Variables and Memory Management in Java Stack vs Heap |
public class HeapExample {
public static void main(String[] args) {
Student student = new Student(); // Object stored in the heap
student.setName("Aarav");
student.greet();
}
}
class Student {
String name;
void setName(String name) {
this.name = name;
}
void greet() {
System.out.println("Hello, my name is " + name);
}
}
Key Points
- Stack Memory: Stores local variables and method calls. Each method call creates a new stack frame, which is removed when the method completes.
- Heap Memory: Stores objects created with
new
and is managed by the Garbage Collector.
![]() |
Parameters vs Arguments in Method Java |