ArchitectMind
  1. Home
  2. Java Ecosystem
  3. Book 1 · Core Java & Modern Java
  4. Volume I
  5. Variables
Book 1 · Volume I — Java Language Fundamentals & Object-Oriented Programming · Topic 2.3

Variables

Local, instance and static variables — initialisation, scope and lifetime

13 min readStage 1 · Foundations14 interview questions
Prerequisites
2.1 Program Structure · 2.2 Identifiers & Keywords
Covers
Local variables · Instance variables · Static variables · Variable initialization · Variable scope · Variable lifetime
Related
3.3 Primitive vs Reference · 4.2 Objects · 8.2 Local Classes (captured variables) · Book 2 Vol IV (Java Memory Model)
On this page
  1. 1. Concept / Definition
  2. 2. Why It Exists
  3. 3. Core Concepts
  4. 4. How It Works Internally
  5. 5. APIs / Features / Syntax
  6. 6. Practical Examples
  7. 7. Common Problems & Mistakes
  8. 8. Performance & Production Considerations
  9. 9. Architecture & Design Considerations
  10. 10. Interview Questions & Answers
  11. Key Takeaways

1Concept / Definition

A variable is a named storage location with a fixed type. Java has three main kinds, distinguished by where they are declared, which in turn decides where the value is stored, who can see it and how long it exists.

KindDeclaredOne copy perStoredDefault value
Local variable (incl. parameters)Inside a method, constructor or blockMethod callThread stack frameNone — must be assigned
Instance variable (field)In a class, without staticObjectInside the object on the heap0, false or null
Static variable (class field)In a class, with staticClassWith the class (HotSpot: in its Class object on the heap)0, false or null
Locals live in stack frames, instance fields inside objects, static fields with the class
Figure 1 — Locals live in stack frames, instance fields inside objects, static fields with the class

2Why It Exists

The three kinds map to three kinds of state a program needs: temporary working values for one computation (locals), the state of each individual object (instance fields), and state shared by all objects of a class (static fields). Separating them lets the compiler and JVM manage memory automatically — a stack frame disappears when its method returns — and makes the sharing of state visible in the code.

3Core Concepts

Local variables

Locals are declared inside a method, constructor or block, including method parameters, loop variables and catch parameters. Each call gets its own copy in its own stack frame, so locals are confined to one thread. Note the subtlety: a local reference is thread-confined, but the object it points to lives on the heap and may be shared.

Since Java 10, var lets the compiler infer the type of a local from its initialiser: var orders = new ArrayList<Order>();. The variable is still statically typed. var works only for locals with an initialiser (and lambda parameters); it is not allowed for fields, method parameters or return types, and var x = null; is illegal because no type can be inferred.

Instance variables

Instance variables are fields declared without static. Every object has its own copy, stored inside the object on the heap, and together they form the object's state. They are accessed through a reference (order.total, or this.total inside the class).

Static variables

Static variables are fields declared with static. There is exactly one copy per class (strictly, per class loaded by a given class loader), shared by every instance and every thread. static final fields with constant values are the usual way to define constants. In HotSpot, static field values are stored with the class's java.lang.Class object on the heap, while class metadata lives in metaspace.

Variable initialization

Fields are always initialised: if you do not assign them, they get default values (0, 0.0, false, '\u0000' or null). Local variables have no default. The compiler's definite assignment rule requires every path to assign a local before it is read; otherwise compilation fails.

Fields receive defaults; locals must be definitely assigned
Figure 2 — Fields receive defaults; locals must be definitely assigned

final means a variable can be assigned only once. A local that is never reassigned, even without final, is effectively final — the condition for being used inside a lambda or anonymous class (Chapter 8).

Variable scope

Scope is the region of source code where a name can be used. A local is in scope from its declaration to the end of its enclosing block; a parameter throughout its method; a field throughout its class. A local with the same name as a field shadows the field, which is why constructors commonly write this.name = name;.

Nested scopes: class, method, loop and if block
Figure 3 — Nested scopes: class, method, loop and if block

Variable lifetime

Lifetime is how long the storage exists at run time, which is different from scope. A local's storage exists for the duration of the method call. An instance field exists as long as its object is reachable. A static field exists as long as its class is loaded — for most applications, the whole life of the process.

Lifetime of static fields, instance fields and locals
Figure 4 — Lifetime of static fields, instance fields and locals

4How It Works Internally

javac assigns each local variable a numbered slot in the method's local-variable array, as seen in 1.2 (istore_1, iload_2). Scope is enforced only by the compiler; the class file does not need names at all unless debug information is included. At run time the JIT usually keeps locals in CPU registers, which is one reason local variables are the cheapest storage in Java. Instance fields are read with getfield/putfield at fixed offsets inside the object; static fields with getstatic/putstatic, which also trigger class initialisation on first use.

Definite assignment is a flow analysis in javac: it follows every path through the method and rejects a read that some path could reach before an assignment. The verifier repeats a simpler version when the class is loaded, so no bytecode, whoever produced it, can read an uninitialised slot. Capture works by copying: a lambda that uses a local receives its current value as an argument when the lambda object is created, and an anonymous or local class stores it in a hidden final field. Because only the value travels, the language requires the local to be effectively final; otherwise the copy and the original could silently disagree.

5APIs / Features / Syntax

JAVAvar, final and unnamed variables
var total = 0.0;                 // inferred double
var names = new ArrayList<String>();
for (var line : order.lines()) { … }
final int limit = 10;            // cannot be reassigned
var _ = queue.poll();            // Java 22+: side effect wanted, value unused
for (Order _ : orders) count++;  // Java 22+: unnamed loop variable

6Practical Examples

Example 1 — Shadowing and this

JAVACustomer.java
public class Customer {
    private String name;                 // instance variable

    public Customer(String name) {       // parameter shadows the field
        this.name = name;                // this.name = field, name = parameter
    }

    public void rename(String newName) {
        name = newName;                  // no shadowing: refers to the field
    }
}

Example 2 — Mini program: the three kinds of variable in one run

Problem. Sections 1 to 3 describe locals, instance fields and static fields separately. This program uses all three in one class and prints their values at each step, so that the difference in copies, defaults and lifetime is visible in the output.

JAVAVariableKinds.java
public class VariableKinds {
    static int created;                   // static: one copy, default 0
    static String lastVisitor;            // static: default null
    final int id;                         // instance: one copy per object
    int visits;                           // instance: default 0
    final String name;
 
    VariableKinds(String name) {          // parameter: a local variable
        this.name = name;
        id = ++created;
    }
 
    VariableKinds visit() {
        int before = visits;              // local: exists only during this call
        visits = before + 1;
        lastVisitor = name;
        return this;                      // the object outlives the call
    }
 
    public static void main(String[] args) {
        System.out.println("start: created=" + created
                + ", lastVisitor=" + lastVisitor);
        var a = new VariableKinds("asha");
        var b = new VariableKinds("ravi");
        a.visit().visit();
        b.visit();
        System.out.println("a: id=" + a.id + ", visits=" + a.visits);
        System.out.println("b: id=" + b.id + ", visits=" + b.visits);
        System.out.println("shared: created=" + created
                + ", lastVisitor=" + lastVisitor);
        for (int i = 1; i <= 2; i++) {
            int square = i * i;           // a fresh 'square' in every iteration
            System.out.println("i=" + i + ", square=" + square);
        }
        // System.out.println(square);    // error: out of scope
    }
}
OUTPUT
start: created=0, lastVisitor=null
a: id=1, visits=2
b: id=2, visits=1
shared: created=2, lastVisitor=ravi
i=1, square=1
i=2, square=4

Why it behaves this way. The first line runs before any object exists: the static fields already have their defaults, 0 and null, because they belong to the class. Each object then gets its own id and visits, while created and lastVisitor are shared, so the last visit, by ravi, overwrites the value asha set. before is a new local in every call of visit, and square a new local in every loop iteration; neither exists after its block. visit returns this, so the object itself outlives the call, which is what allows a.visit().visit().

Example 3 — Definite assignment

JAVACompiler-enforced initialisation
int discount;
if (customer.isPremium()) {
    discount = 10;
}
return price - discount;   // compile error: variable discount might not
                           // have been initialized

int safeDiscount = customer.isPremium() ? 10 : 0;   // assigned on every path

Example 4 — Static versus instance state

JAVAOrder.java
public class Order {
    private static int nextId = 1;   // one counter shared by all orders
    private final int id;            // one id per order

    public Order() {
        this.id = nextId++;          // not thread-safe: see section 9
    }
}

Example 5 — Effectively final capture

JAVALambdas can capture only effectively final locals
int threshold = 100;
orders.removeIf(o -> o.total() < threshold);  // OK: effectively final
threshold = 200;          // now the lambda above no longer compiles

Example 6 — Loop variables and lambdas

Problem. Example 5 shows that a lambda can capture only an effectively final local. In loops this rule surprises people: the counter of a classic for loop cannot be captured, but the variable of an enhanced for can.

JAVACaptureLoop.java
import java.util.ArrayList;
import java.util.List;
import java.util.function.Supplier;
 
public class CaptureLoop {
    public static void main(String[] args) {
        List<Supplier<String>> tasks = new ArrayList<>();
        for (int i = 1; i <= 3; i++) {
            // tasks.add(() -> "task " + i); // error: i is not final
            int n = i;                       // a fresh, final copy
            tasks.add(() -> "task " + n);
        }
        for (String day : List.of("mon", "tue")) {
            tasks.add(() -> "report " + day);  // fine: a new day each time
        }
        int[] calls = {0};                     // an array element can change...
        tasks.forEach(t -> calls[0]++);        // ...but it hides shared state
        tasks.forEach(t -> System.out.println(t.get()));
        System.out.println("tasks: " + calls[0] + ", or " + tasks.size());
    }
}
OUTPUT
task 1
task 2
task 3
report mon
report tue
tasks: 5, or 5

Why it behaves this way. i is changed by i++ after each iteration, so it is not effectively final, and the commented line does not compile. Copying it into n, a new local in each iteration, gives each lambda its own value. The enhanced for declares a new day for each element, so it is effectively final without a copy. The one-element array compiles because the reference calls never changes, only its content; it works here, but it is shared mutable state in disguise, and inside a parallel stream or another thread it races exactly like the field in Example 7.

Example 7 — The singleton race, measured

Problem. Section 9 shows a service that keeps a running total in a field. This program runs that design and the fixed one on 8 threads, 400 requests each, with a cart of 10,000 items worth 1 each, and counts the wrong totals.

JAVAPricingRace.java
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.concurrent.*;
import java.util.function.Function;
 
public class PricingRace {
    static class FieldPricing {                // section 9: a field
        private BigDecimal runningTotal;
        BigDecimal price(List<BigDecimal> lines) {
            runningTotal = BigDecimal.ZERO;
            for (BigDecimal p : lines) runningTotal = runningTotal.add(p);
            return runningTotal;
        }
    }
 
    static class LocalPricing {                // the fix: a local
        BigDecimal price(List<BigDecimal> lines) {
            BigDecimal total = BigDecimal.ZERO;
            for (BigDecimal p : lines) total = total.add(p);
            return total;
        }
    }
 
    static int wrong(Function<List<BigDecimal>, BigDecimal> pricer,
                     List<BigDecimal> cart) throws Exception {
        try (ExecutorService pool = Executors.newFixedThreadPool(8)) {
            List<Future<BigDecimal>> results = new ArrayList<>();
            for (int i = 0; i < 400; i++)
                results.add(pool.submit(() -> pricer.apply(cart)));
            int wrong = 0;
            for (Future<BigDecimal> f : results)
                if (f.get().intValue() != cart.size()) wrong++;
            return wrong;
        }
    }
 
    public static void main(String[] args) throws Exception {
        List<BigDecimal> cart = Collections.nCopies(10_000, BigDecimal.ONE);
        int field = wrong(new FieldPricing()::price, cart);
        int local = wrong(new LocalPricing()::price, cart);
        System.out.println("field: " + field + " of 400 wrong");
        System.out.println("local: " + local + " of 400 wrong");
    }
}

Output of one run (the first number changes from run to run):

OUTPUT
field: 271 of 400 wrong
local: 0 of 400 wrong

Why it behaves this way. All threads share the one FieldPricing object, so each request resets and adds to the same runningTotal; a request returns whatever the field holds when its own loop ends. How many results are wrong depends on timing and the number of CPUs, which is why such a bug can pass every single-threaded test and appear only under load. LocalPricing keeps the total in a local variable, which lives in each thread's own stack frame, so it is correct every time without any synchronisation (Figure 5).

7Common Problems & Mistakes

MistakeWhy it hurtsBetter approach
Forgetting this. in a constructor (name = name;)Assigns the parameter to itself; the field stays nullUse this.name = name; enable the IDE/compiler warning
Mutable static fields as global stateHidden coupling, thread-safety bugs, tests affecting each otherInject shared state explicitly; keep statics final and immutable
Assuming a local variable makes an object thread-safeOnly the reference is confined; the object may be sharedReason about the object, not the variable
var with an unclear initialiser (var x = service.process();)Readers cannot see the typeUse var when the type is obvious from the right-hand side
Large objects referenced from static fieldsLive for the whole process; common memory-leak sourceBound caches, clear references, use a cache library
Working around effectively final with a one-element array or AtomicIntegerIt compiles, but it hides shared mutable state that races as soon as the lambda runs on another threadCopy the value into a new local, or return results instead of mutating (Example 6)
Relying on the default null of a fieldThe NullPointerException appears far from the constructor that forgot to set itAssign every field in the constructor and make it final, so the compiler checks it
ThreadLocal set per request on a pooled thread and never clearedThe next request on that thread sees the previous user's data; the values also leak memoryClear it in finally, or use a ScopedValue (Java 25), whose binding ends with its scope (Q12)

8Performance & Production Considerations

  • Locals are the cheapest storage: usually registers after JIT compilation, and the JIT's escape analysis can even avoid heap allocation for objects that never leave a method.
  • Static collections are a leading cause of memory leaks because their lifetime is the process lifetime.
  • Shared mutable fields need synchronisation, atomics or immutable design; unsynchronised updates are lost under load (Book 2 Volume IV).

9Architecture & Design Considerations

In frameworks such as Spring, most components are singletons: one instance serves every request on every thread. For such a component, an instance field behaves like shared global state. A field used to hold per-request data — the current user, a running total — becomes a race condition under concurrent load.

JAVAA singleton service with per-request state in a field
@Service
public class PricingService {
    private BigDecimal runningTotal;          // BUG: shared by all requests

    public BigDecimal price(Cart cart) {
        runningTotal = BigDecimal.ZERO;       // request A resets…
        for (var line : cart.lines()) {
            runningTotal = runningTotal.add(line.price());   // …while B adds
        }
        return runningTotal;
    }
}
Locals live in each thread's frame; the fields of a singleton are shared by every request
Figure 5 — Locals live in each thread's frame; the fields of a singleton are shared by every request

Figure 5 shows why the bug appears only under concurrency: the two requests have separate frames, but runningTotal exists once, in the one bean on the heap. Example 7 measures it.

10Interview Questions & Answers

Q1L1 · BasicConcept

What are the three kinds of variables in Java?

Local variables (declared in methods, constructors or blocks, including parameters), instance variables (non-static fields, one copy per object) and static variables (static fields, one copy per class).

Q2L1 · BasicConcept

Do local variables have default values?

No. Fields receive default values, but locals must be definitely assigned before they are read; the compiler rejects code where some path could read an unassigned local.

Q3L2 · IntermediateConcept

What is the difference between scope and lifetime?

Scope is where a name is visible in the source code, enforced by the compiler. Lifetime is how long the storage exists at run time. A local's scope is its block; an object it references can outlive the method if the reference escapes, for example by being stored in a field or returned.

Q4L2 · IntermediateConcept

What does effectively final mean and where does it matter?

A local variable that is never reassigned after initialisation, even without the final keyword. Lambdas and anonymous or local classes can capture only final or effectively final locals, because they receive a copy of the value.

Q5L3 · Senior EngineerTricky

Does var make Java code dynamically typed? Where can it be used?

No — the type is inferred at compile time and fixed. var is allowed for local variables with an initialiser, enhanced-for and try-with-resources variables, and lambda parameters. It is not allowed for fields, method parameters, return types, or with a null initialiser.

Q6L3 · Senior EngineerScenario

A Spring service returns wrong totals only under load. The code works in unit tests. What would you look for?

Per-request state stored in fields of a singleton bean. Under concurrent requests, threads overwrite each other's field values; single-threaded tests never show it. The fix is to move that state into local variables or parameters, leaving fields for dependencies and immutable configuration.

Q7L4 · Technical ArchitectDesign

Why do many architecture guidelines discourage mutable static state?

Static state is global: any code can change it, which creates hidden coupling between components, makes behaviour depend on execution order, breaks test isolation, requires synchronisation under concurrency and lives for the whole process, so it can also leak memory. Explicitly injected, scoped state is easier to reason about, test and scale.

Q8L2 · IntermediateCode

What does this program print?

JAVADefaults.java
public class Defaults {
    static int count;
    static double rate;
    static boolean active;
    static char code;
    static String name;
 
    public static void main(String[] args) {
        System.out.println(count + " " + rate + " " + active + " "
                + (int) code + " " + name);
    }
}

It prints 0 0.0 false 0 null. Static and instance fields that are never assigned hold their default values: 0 for numbers, 0.0 for floating point, false, the char with code 0 and null for references. The char is printed as (int) code because the character \u0000 itself is invisible. The same code with local variables instead of fields would not compile, since locals have no defaults.

Q9L3 · Senior EngineerCode

What does this program print?

JAVAShadowQuiz.java
public class ShadowQuiz {
    private String name = "unknown";
 
    ShadowQuiz(String name) {
        name = name;              // assigns the parameter to itself
    }
 
    public static void main(String[] args) {
        System.out.println(new ShadowQuiz("asha").name);
    }
}

It prints unknown. Inside the constructor the parameter name shadows the field, so name = name assigns the parameter to itself and the field keeps its initial value. With a field without an initialiser the result would be null. javac accepts it silently; IDEs and tools such as Error Prone flag a self-assignment, and this.name = name is the fix. Making the field final turns the mistake into a compile error, because a final field must be assigned in the constructor.

Q10L3 · Senior EngineerTricky

Can a local variable be declared again with the same name inside a nested block? And in a sibling block?

JAVANestedRedeclare.java
public class NestedRedeclare {
    static void run() {
        int total = 0;
        for (int i = 0; i < 3; i++) {
            int total = i;          // compile error: total is already defined
        }
        { int step = 1; }
        { int step = 2; }           // fine: the first step is out of scope
    }
}

Not in a nested block: javac reports "variable total is already defined in method run()", because Java, unlike C, forbids a local from shadowing another local that is still in scope. Sibling blocks are fine, since the first step is out of scope when the second is declared, and the compiler may even give both the same slot. A local may shadow a field, which is legal and the reason this. exists.

Q11L3 · Senior EngineerInternals

Where does HotSpot store static fields, and what triggers their initialisation?

Class metadata lives in metaspace, but the values of static fields are stored with the class's java.lang.Class object on the heap, so they are reachable for as long as the class is loaded. They are set during class initialisation, which happens once, on the first active use: creating an instance, calling a static method, or reading or writing a static field that is not a compile-time constant. getstatic and putstatic trigger it if it has not happened yet; reading a static final constant does not, because javac copied the value into the caller.

Q12L4 · Technical ArchitectTrade-off

Request context such as the current user or a trace id: pass it as a parameter, keep it in a ThreadLocal or use a ScopedValue?

Parameters are explicit and testable, and every method signature shows what it depends on, but threading a context object through many layers is noisy. A ThreadLocal avoids that, at the cost of hidden coupling, values that leak to the next request on a pooled thread unless cleared in finally, and poor behaviour with millions of virtual threads. A ScopedValue, final in Java 25, binds a value for the duration of a call, ScopedValue.where(USER, u).run(...), is immutable and is inherited by structured subtasks. A good rule is parameters for business data, a ScopedValue for cross-cutting context, and ThreadLocal only where a framework still requires it.

Q13L5 · Solution ArchitectDesign

What rules would you set for where state may live in a fleet of stateless services?

Per-request data lives in local variables, parameters and request-scoped objects that die with the request. Fields of singleton components hold only dependencies and immutable configuration, and static fields only constants. Anything that must survive a request or be shared between instances goes outside the process: a database for the system of record, a distributed cache with a time to live for derived data, a message broker for work in progress. In-process caches are allowed only with a size bound and an expiry, and are treated as disposable. These rules are what make horizontal scaling, rolling deployments and restarts safe, and they can be checked with ArchUnit rules on fields.

Q14L5 · Solution ArchitectScenario

A service's heap grows steadily over several days until it fails with OutOfMemoryError. A heap dump shows a static HashMap holding two million entries. How do you handle it, now and for the platform?

Now: find who writes to the map, from the reference chain in the dump, and why entries are never removed; usually it is a cache or registry keyed by request, session or user. Replace it with a bounded cache with expiry, such as Caffeine, or remove entries at the end of their life, and restart the affected instances. For the platform: alert on old-generation occupancy after full collections rather than on total heap, capture heap dumps automatically on OutOfMemoryError, and add a static-analysis or ArchUnit rule that flags mutable static collections, so the next one is caught in review instead of in production.

Test your knowledge on this topic →Flashcards from this topic's 14 questions, filtered by level and type.

Key Takeaways

  • Locals live in stack frames and are thread-confined; fields live in objects; statics live with the class and are shared by everything.
  • Fields get defaults; locals must be definitely assigned.
  • Scope is compile-time visibility; lifetime is run-time existence.
  • In singleton components, fields are shared state — keep per-request data in locals.
Free question pack

Get 100 free Core Java interview questions

Subscribe for the Book 1 question pack (PDF, every answer explained) and new tutorials once a week. No spam, unsubscribe anytime. What is in the pack?

Almost done! Check your inbox and click the confirmation link. Your download link arrives as soon as you confirm.