Interview Q&A · Java · 4 questions in this topic
Variable Scope, Lifetime and Memory — Java Interview Q&A
How long each kind of variable lives, where it is visible, and where it sits in memory. Part of Objects, References & Memory · 294 questions in the Java bank.
What is the scope and lifetime of instance variables?
Answer
An instance variable belongs to one object and is visible to every non-static method of that object. It is created when the object is created with new and lives on the heap as part of the object. It stays alive as long as the object is reachable and becomes eligible for collection with it.
What is the scope and lifetime of static (class) variables?
Answer
A static variable belongs to the class itself, so there is exactly one copy shared by all instances. It can be used even before any object is created and is visible wherever its access modifier allows. It lives for the lifetime of the loaded class, which in practice means the whole application run.
What is the scope and lifetime of local variables?
Answer
A local variable is declared inside a method or block and is visible only within that block. It is created in the stack frame when its declaration executes and disappears when the block exits. The compiler also requires definite assignment, so a local must be assigned before it is read.
Example
void demo() { int x = 1; // created here in the stack frame if (x > 0) { int y = x + 1; // visible only inside this block } } // x and y are gone here
Where are variables created in memory?
Answer
Objects always live on the heap, while primitives and references live wherever they are declared. Local variables sit in the thread stack frame, and instance or static fields sit inside their heap objects or class data. When a method exits, its stack frame is discarded, which is why locals vanish automatically. Modern JVMs may use escape analysis to keep some short-lived objects on the stack, but the mental model of stack for locals and heap for objects still holds.
Key points
- 1Heap: all objects plus the fields inside them.
- 2Stack: one frame per call holding locals and partial results.
- 3References are handles: the handle lives where declared, the object lives on the heap.
Learn this topic
Recommended resourcesAffiliate links · may earn us a commission