public class Demo {
public static void main(String[] args) {
int x = 5;
Point p = new Point(1, 2);
}
}
class Point {
int x, y;
Point(int x, int y) { this.x = x; this.y = y; }
}Where do the local variable
x and the Point object referenced by p live in the JVM's memory areas?- aBoth
xand thePointobject live on the heap; onlypitself lives in the stack frame - b
xandpsit in the stack frame; only thePointobject lives on the heap✓ - cBoth
xand thePointobject live insidemain's stack frame - d
xlives on the heap, while thePointobject andpboth live on the stack
Explanation:Each thread has its own stack made up of frames, one per active method call. Primitive local variables like
x are stored directly inside the current frame. Reference variables like p are also stored in the frame, but the object they point to -- here, the Point instance created by new -- is allocated on the shared heap, which all threads can reach. When main returns, the frame (and x, p) disappear, but the Point object only goes away once nothing references it anymore and the garbage collector reclaims it.