Interview Q&A · Java · 4 questions in this topic

Variable Scope, Lifetime and Memory — Java Interview Q&A

All Java topics

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

Example.javajava
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

Recommended resourcesAffiliate links · may earn us a commission

Classic DSA interview booksThe reference books interviewers themselves learned from — great next to the visualizers.See the books Structured coding coursesVideo courses that pair well with visual practice — pick one language and go deep.Browse courses Cloud hosting for side projectsShip the portfolio project that gets you hired — free credits for new accounts.Claim credits