skip to content

Local, Instance & Static Variables

Locals live on the stack for the length of a method, instance fields live with the object on the heap, and statics exist once per class. Interviewers ask you to place a given variable and explain who can see it and how long it lives.

part ofJavaoverview, primer and where to startread it →
on this pageshow

questions

5

What are the three kinds of variables in Java, and how do they differ in where they live and how long they exist?

level: juniorimportance: must knowfreq 85%

answer

  1. Local = stack, per-call, no default
  2. Instance = heap, per-object, auto default
  3. Static = class area, one copy, shared
  4. Local must be assigned before use
  5. Parameters are local variables

basics

~20 s

Local variables live inside a method and disappear when it ends. Instance variables belong to each object and live as long as the object. Static variables belong to the class itself, so there is just one copy shared by everything.

solid answer

~40 s

Java has three variable kinds. Local variables are declared inside a method, constructor, or block; they live on the call stack and exist only while that method runs, so each call gets its own copy. Instance variables (non-static fields) are declared in the class body; each object created from the class gets its own copy, stored on the heap as part of the object, and they live as long as the object is reachable. Static variables (class variables, marked static) are declared with the static keyword; there is exactly one copy per class, created when the class is loaded and shared by all instances. A key practical difference: instance and static variables get default values (0, false, null) automatically, while local variables do not and must be assigned before use.

go deeper

for a junior

Name the three kinds and state the simple rule: local = inside a method, instance = per object, static = one shared copy for the class.

for a middle

Tie each kind to its memory region (stack/heap/class area) and lifetime, and explain default values vs. definite assignment for locals.

for a senior

Discuss implications: thread-safety of shared static state, GC eligibility tied to object reachability, and that parameters are locals.

for a principal

Reason about static state as hidden global mutable state (testability, memory leaks via long-lived statics, class-loading/unloading semantics) and guide team conventions.

## What a variable is A **variable** is a named storage location that holds a value. In Java, where that storage lives, who owns it, and how long it lasts depend on *how and where* you declare it. There are three kinds. ### 1. Local variables A **local variable** is declared inside a method, constructor, or a block (anything between `{ }` such as a loop or `if`). It is *method-scoped*: it only exists from its declaration to the end of the enclosing block. - **Where it lives:** the **call stack**. Each method invocation creates a *stack frame* holding that call's local variables. When the method returns, the frame is popped and the locals vanish. - **Lifetime:** only while the method (or block) is executing. Two calls to the same method each get their own, independent locals — that is why recursion works. - **Default value:** *none*. The compiler refuses to compile if you read a local variable that might not have been assigned ("variable might not have been initialized"). You must initialize it yourself. - **Includes** method parameters (they are local variables initialized from the caller's arguments). ### 2. Instance variables (non-static fields) An **instance variable** is declared directly in the class body *without* the `static` keyword. It is also called a *field* or *member variable*. - **Where it lives:** on the **heap**, as part of each object. Every `new` creates a fresh object with its own set of instance variables. - **Lifetime:** tied to the object. It comes into existence when the object is created and is eligible to be garbage-collected when the object becomes unreachable. - **Default value:** automatically initialized — numeric types to `0`/`0.0`, `boolean` to `false`, `char` to `''`, and reference types to `null`. You can read them without explicit assignment. - **One copy per object:** `dog1.name` and `dog2.name` are independent. ### 3. Static variables (class variables) A **static variable** is declared in the class body *with* the `static` keyword. - **Where it lives:** in the class's metadata area (historically called the method area / metaspace), not inside any object. - **Lifetime:** there is exactly **one** copy per class. It is created when the class is first loaded by the JVM and lives until the class is unloaded (usually for the whole program run). - **Default value:** same automatic defaults as instance variables. - **Shared:** all instances and all code see the *same* variable. Changing it through one object changes it for everyone. Access it via the class name (`Counter.count`) — that is the idiomatic form. ### Putting it together ```java class Counter { static int total; // static: one copy for the whole class int id; // instance: one copy per Counter object void record() { int delta = 1; // local: fresh each call, lives only here total += delta; id += delta; } } ``` If you make two `Counter` objects and call `record()` on each, `total` ends at 2 (shared), while each object's `id` ends at 1 (per-object), and `delta` is created and destroyed twice (per-call). ### Mental summary | Kind | Declared | Lives in | One copy per | Auto default? | |------|----------|----------|--------------|---------------| | Local | inside method/block | stack | method call | No | | Instance | class body, no `static` | heap (in object) | object | Yes | | Static | class body, `static` | class area | class | Yes |

  • Why must you initialize a local variable but not an instance variable?
    Instance and static variables get automatic default values when their object/class is created. Local variables are not auto-initialized, so the compiler enforces definite assignment to avoid reading garbage from the stack.
  • Are method parameters local variables?
    Yes. Parameters are local variables whose initial value is supplied by the caller's argument; they live on the stack frame and disappear when the method returns.

saying these in an interview costs you the question

  • Saying static variables get one copy per object (they are one per class)
  • Claiming local variables get default values (they do not — compiler error)
  • Confusing 'static' with 'constant' (static can change; final makes it constant)
  • Saying instance variables live on the stack

context

open as a page

Why can a static method not directly access instance variables, but an instance method can access static variables?

level: juniorimportance: should knowfreq 50%

basics

~20 s

A static method belongs to the class, not to any object, so it has no specific object whose instance variables it could read. An instance method already runs on an object, and since there is one shared static variable per class, it can reach that too.

open as a page

Explain variable scope in Java: what determines where a variable is visible, and what happens when names overlap (shadowing)?

level: middleimportance: should knowfreq 60%

basics

~20 s

A variable is visible only inside the block of curly braces where it is declared, plus any blocks nested inside it. If a local variable has the same name as a field, the local one wins inside that block; this is called shadowing.

open as a page

What are the practical risks of using static (class) variables for mutable shared state, especially in multithreaded code?

level: seniorimportance: should knowfreq 55%

basics

~20 s

A static variable is one shared copy for the whole program. If several threads change it at once you can get wrong results, and it can cause hard-to-test code and memory leaks because it stays alive for the whole run.

open as a page

In what order are static variables, instance variables, and their initializer blocks set up when a class is first used and an object is created?

level: seniorimportance: nice to knowfreq 35%

basics

~20 s

Static parts run once when the class is first loaded, top to bottom. Then, every time you create an object, the instance fields and instance blocks run top to bottom, and finally the constructor body runs.

open as a page