Stack frames
Description
Each method call has local working space.
Explanation
When the method returns, its local frame is removed.
Example
int score = 90;← Chapter 5 — Arrays, Memory & Methods
mixed
Java manages memory automatically, but a simple mental model helps you understand variables. Local variables and method calls are associated with the stack, while objects and arrays live on the heap.
A reference variable holds a way to reach an object, not a full copy of that object. Multiple references can point to the same object.
Each method call has local working space.
When the method returns, its local frame is removed.
int score = 90;Objects are created with new.
Garbage collection may reclaim unreachable objects.
int[] scores = new int[3];Do not try to manually free Java objects. Instead, avoid retaining references you no longer need and use try-with-resources for files, sockets, and similar resources.
public class MemoryDemo {
public static void main(String[] args) {
int[] scores = {70, 80, 90};
int[] sameScores = scores;
sameScores[0] = 75;
System.out.println(scores[0]);
}
}