Java Variables and Constants

Understand Java variables, Java 10 local type inference, final references, and the rules for compile-time constants and static fields.

published: reading time: 20 min read author: Geek Workbench updated: November 20, 2026
Quick Summary

Understand Java variables, Java 10 local type inference, final references, and the rules for compile-time constants and static fields.

Java Variables and Constants

Java variables have declared types and scopes. var can infer a local variable’s type from its initializer (Java 10+), while final limits reassignment. The distinction matters: final can suggest more protection than it provides if you assume the referenced object is frozen.

Introduction

The examples that use local-variable type inference with var require Java 10 or later. List.of examples require Java 9 or later. Compile-time constant expressions are not a Java 10 feature; their rules are defined by the Java Language Specification.

Use var for local type inference when the initializer makes the type clear. Use final when you want the compiler to reject reassignment. static final marks a class variable that cannot be reassigned, but only some such fields qualify as compile-time constants.

final constrains assignment, not the state of the referenced object. A final list can still accept additions. Compile-time constants have a narrower definition: the JLS requires a final primitive or String variable initialized with a constant expression.

This guide covers local type inference, final assignment rules, field initialization, and the difference between constant variables and other static final fields.

When to Use / When Not to Use

Use var (Java 10+) when:

  • Type is obvious from the right-hand side (constructor, method return)
  • Reducing verbosity improves readability
  • Working with complex generic types

Use final when:

  • A variable should not be reassigned after initialization
  • You want to prevent reassignment of the variable
  • Making defensive copies of parameters

Use static final when:

  • Defining shared compile-time constants of primitive or String type
  • Configuration values that never change
  • Singleton pattern implementations

Avoid overusing:

  • var when type is not immediately clear (harms readability)
  • final on parameters when not needed (adds noise)
  • static final for values that might need configuration changes

Variable Declaration Flow

graph LR
    A["Declaration<br/>int x;"] --> B["Assignment<br/>x = 5;"]
    B --> C["Read<br/>x + 10"]

    E["final var (Java 10+)"] --> F["Type inferred"]
    F --> G["Variable cannot be reassigned"]

    H["static final"] --> I["Reference or value cannot be reassigned"]
    I --> J["Constant variable only for eligible primitive/String expressions"]

final applies to the variable, not automatically to the object it refers to:

final List<String> names = new ArrayList<>();
names.add("Ada"); // allowed: the list reference is unchanged
// names = new ArrayList<>(); // compile-time error: reassigns a final variable

Production Failure Scenarios

Scenario Cause Mitigation
Accidental reassignment A variable changes when it should not Use final where it states an assignment contract
Uninitialized variable Local variable used before assignment Initialize at declaration or in the constructor
Confusing var type Inferred type is not obvious Use var only when the type is clear from context
Mutable constant collections static final List still permits list mutation Use an immutable list or an unmodifiable defensive copy
// Common mistakes and fixes

// BAD: Mutable constant that can be modified
static final List<String> CONFIG = new ArrayList<>();
CONFIG.add("data"); // This compiles! List reference is final, not contents

// GOOD: Truly immutable list
static final List<String> CONFIG = Collections.unmodifiableList(
    List.of("data")
);

// Java 10+: var hides an unclear type here
var result = complexCalculation(); // What type is this?

// GOOD: Explicit type for complex operations
List<Customer> result = fetchCustomersByRegion(region);

// BAD: Shadowing variable
int count = 10;
{
    int count = 20; // Compiler error in Java, but possible in other languages
}

// GOOD: Clear scoping
int count = 10;
{
    int itemCount = 20;
    // use itemCount
}

Trade-off Table

Declaration Reassignable Initialization Scope
var (Java 10+) Yes Required before use Local only
final var No Required at declaration Local only
final field No In constructor or declaration Instance
static final No Declaration or static block Class

Implementation Snippets

Variable Declaration Patterns

Java lets you write a local type explicitly or use var (Java 10+) when the initializer makes the type clear. final prevents reassignment; it does not make a referenced object immutable. static final is also used for class variables, but only eligible primitive and String fields initialized with constant expressions are constant variables under the JLS.

public class VariablePatterns {
    // Instance variables - initialized to defaults
    private String name;
    private int age;
    private final Date createdAt;

    // Constructor initialization for final fields
    public VariablePatterns(String name, int age) {
        this.name = name;
        this.age = age;
        this.createdAt = new Date(); // final must be initialized here
    }

    public void demonstrate() {
        // Local variables - must be initialized
        int count;                      // Declared but not initialized
        // System.out.println(count);  // Would not compile

        count = 10;                    // Now initialized

        // Type inference with var
        var message = "Hello";          // String
        var numbers = List.of(1, 2, 3); // List<Integer>

        // Final local variable
        final double PI = 3.14159;
        // PI = 3.0;                   // Would not compile

        // Blank final (initialized later)
        final long timestamp;
        if (someCondition()) {
            timestamp = System.currentTimeMillis();
        } else {
            timestamp = 0;
        }
    }
}

Scope and Shadowing

Scope determines where a variable is visible and accessible. Java has four levels: class (static), instance, method, and block scope. Shadowing happens when an inner variable shares a name with an outer one — the inner takes precedence. Java forbids field shadowing in subclasses (the compiler errors), but locals and parameters can shadow each other. Knowing where scope boundaries sit prevents bugs where you think you’re using one variable but are actually using another.

public class ScopeDemo {
    private int field = 1;  // Instance scope

    public void method(int param) {  // Method scope
        int local = 2;              // Local scope

        if (true) {
            int blockVar = 3;        // Block scope

            // Shadowing: same name, different scope
            int field = 999;         // ERROR: conflicts with instance field
            int param = 100;         // ERROR: conflicts with method param
        }
        // blockVar not accessible here

        System.out.println(field);   // Refers to instance field (1)
        System.out.println(param);   // Refers to method parameter
        System.out.println(local);   // Refers to local variable
    }
}

Static Final Constants

static final declares a class variable that cannot be reassigned after initialization. A field is a JLS constant variable only when it is final, has primitive or String type, and is initialized with a constant expression. Other static final fields are initialized at run time; if one refers to a mutable object, that object’s state may still change.

public class Constants {
    // Compile-time constant variable: primitive type + constant expression
    public static final int MAX_CONNECTIONS = 100;
    public static final String APP_NAME = "GeekWorkBench";

    // A final reference initialized at runtime; Date itself is mutable
    public static final Date START_DATE;

    static {
        START_DATE = new Date();
    }

    // Build the list, then expose it only through an unmodifiable wrapper
    public static final List<String> SUPPORTED_FORMATS;
    static {
        List<String> formats = new ArrayList<>();
        formats.add("JSON");
        formats.add("XML");
        formats.add("CSV");
        SUPPORTED_FORMATS = Collections.unmodifiableList(formats);
    }
}

Observability Checklist

  • Track variable shadowing that causes confusion
  • Monitor final field reassignment attempts (should fail in tests)
  • Log when configuration constants change at runtime
  • Measure memory impact of unused local variables (scope too wide)
  • Alert on attempt to modify unmodifiable collections
// Observability for variable usage
public class VariableMonitor {
    public void trackInitialization(String varName, Object value) {
        if (value == null) {
            Logger.warn("Variable {} initialized with null", varName);
        }
        metrics.record(varName, value);
    }

    public <T> T safeGet(T value, T defaultValue) {
        return (value != null) ? value : defaultValue;
    }
}

Common Pitfalls / Anti-Patterns

  • Final fields and immutability: final prevents field reassignment, but mutable objects still need defensive copying or restricted access.
  • Parameter validation: Mark input parameters final when method should not modify them
  • Constants in security algorithms: Use static final for algorithm parameters that shouldn’t change
  • Audit trail: Consider logging when sensitive configuration values are accessed
// Security patterns for variables
public class SecureConfig {
    // Final fields prevent modification after construction
    private final String apiKey;
    private final int maxRetries;

    public SecureConfig(String apiKey, int maxRetries) {
        // Validate inputs
        if (apiKey == null || apiKey.isBlank()) {
            throw new SecurityException("Invalid API key");
        }
        if (maxRetries < 0 || maxRetries > 10) {
            throw new SecurityException("Invalid retry count");
        }

        this.apiKey = apiKey;
        this.maxRetries = maxRetries;
    }

    // No setters - immutable after construction
    public String getApiKey() { return apiKey; }
    public int getMaxRetries() { return maxRetries; }
}
  1. Not using final for genuinely constant values

    // BAD
    int maxSize = 1000;
    for (int i = 0; i < maxSize; i++) { }  // Could be accidentally modified
    
    // GOOD
    final int MAX_SIZE = 1000;
  2. Var with non-obvious type

    // BAD - what is the type?
    var result = getDataFromService();
    
    // GOOD - type is clear
    List<Transaction> result = getDataFromService();
  3. Final on reference type doesn’t mean immutable contents

    // BAD - contents can change
    final List<String> list = new ArrayList<>();
    list.add("item"); // Perfectly legal
    
    // GOOD - truly immutable
    final List<String> list = List.of("item");
  4. Widening scope unnecessarily

    // BAD - variable lives too long
    String temp;
    if (condition) {
        temp = calculate();
    }
    use(temp); // temp might be uninitialized
    
    // GOOD - narrower scope
    if (condition) {
        String temp = calculate();
        use(temp);
    }

Quick Recap Checklist

  • Local variables must be initialized before use; instance fields have defaults
  • final prevents reassignment but doesn’t make objects immutable
  • var infers type at compile time — works only for local variables
  • A static final field is a constant variable only when its type and initializer meet the JLS rules
  • Reference types marked final can still have their contents modified
  • Use Collections.unmodifiableList() and similar for truly immutable collections
  • Shadowing (same name in nested scope) causes compilation errors
  • Prefer narrowest scope to reduce bugs and improve readability

Interview Questions

1. What is the difference between `final`, `finally`, and `finalize()`?
final is a modifier meaning "cannot be changed" — applies to variables (reassignment prevented), methods (cannot be overridden), and classes (cannot be extended). finally is a block in try-catch-finally that always executes after try/catch, used for cleanup like closing resources. finalize() is a deprecated Object method called by garbage collector before reclaiming memory — it is not a substitute for proper resource cleanup and should not be relied upon.

2. Can a blank final variable be initialized in an if-else block?
Yes, if the variable is marked final and assigned exactly once, you can initialize it conditionally across multiple branches — as long as the compiler can prove all execution paths assign it exactly once. For instance variables, initialization must occur in every constructor. For local variables, all code paths must assign before use.

3. What is the performance impact of using `final`?
Use final to express that a variable is assigned once, not as a general performance hint. Whether a particular final field affects optimization depends on the code and runtime; measure a proven hot path before changing declarations for speed.
4. Why should you use `var` in Java? What are the restrictions?
var enables local variable type inference — the compiler deduces the type from the right-hand side. Use it when the type is obvious and improves readability: var list = new ArrayList<String>(); vs ArrayList<String> list = new ArrayList<String>();. Restrictions: var cannot be used for instance variables, method parameters, or return types. It also cannot be used with lambda expressions or method references where the target type is not yet established.

5. What is the difference between a constant defined with `static final` and an `enum`?
A static final primitive or String is a JLS constant variable only when its initializer is a constant expression. Compilers may embed that value in client bytecode, so clients can need recompilation after the value changes. An enum represents a fixed set of named values with distinct identities. Use an enum when callers should choose among related values; use a constant variable for a value such as MAX_BUFFER_SIZE.
6. What is the difference between instance variables and local variables?
Instance variables (fields) are declared at the class level and have default values (reference types default to null, primitives have type-specific defaults). They live as long as the object lives. Local variables (method variables) are declared inside methods and must be explicitly initialized before use — the compiler will not allow reading an uninitialized local variable. Local variables go out of scope when the method completes. Instance variables are subject to shadowing rules; local variables cannot be shadowed in their own scope but can be shadowed by parameters or inner blocks with the same name.

7. What does the `var` keyword infer in Java 10+?
var enables local variable type inference — the compiler deduces the type from the right-hand side. Use it when the type is obvious and improves readability: var list = new ArrayList<String>(); vs ArrayList<String> list = new ArrayList<String>();. Restrictions: var cannot be used for instance variables, method parameters, or return types. It also cannot be used with lambda expressions or method references where the target type is not yet established.

8. What is a blank final variable?
A blank final variable is a final variable that is not initialized at declaration but is assigned exactly once before use. For instance variables, the blank final must be assigned in every constructor (or in an initializer block if there's only one constructor). For local variables, all code paths must assign before use or the compiler errors. Blank finals allow you to have final guarantees (assigned exactly once) while deferring the value assignment. A common pattern: final int result; if (condition) { result = computeValue(); } else { result = -1; } — the compiler verifies all paths assign exactly once.

9. What is the difference between `final` and `effectively final`?
A variable is effectively final if it is not explicitly marked final but could be — meaning it is never reassigned after initialization. The compiler treats effectively final variables the same as final for the purpose of lambda expressions and anonymous classes — they can be used in closures. A variable is explicitly final if declared with the final keyword. Effective finality is a concept introduced in Java 8 to simplify coding — you don't need to add final everywhere if you never reassign. Note: modifying the contents of a reference (e.g., list.add()) does not make a variable non-effectively-final — only reassignment of the variable itself matters.

10. What is variable shadowing and how do you avoid it?
Variable shadowing occurs when a variable in an inner scope has the same name as a variable in an outer scope. In Java, this is allowed for local variables and parameters, but not for instance variables — declaring a field with the same name as an inherited field causes a compile error. Shadowing makes code confusing — count inside the block refers to the inner variable, not the outer one. To avoid: use distinct names, minimize scope widths, and be explicit about which variable you're referencing (this.count for instance fields vs local parameters). Modern IDEs warn about shadowing. The compiler will error on field shadowing in subclasses.

11. Can you declare a variable as `static var`?
No — var is only valid for local variable declarations (inside methods, constructors, or initializer blocks). You cannot use var for instance variables, static variables, method parameters, or return types. This restriction exists because var relies on type inference from an initializer expression, and these other contexts either lack initializers at the declaration site or would create ambiguous situations for the compiler. Use explicit types for all class-level and method-signature declarations.

12. What is the default value of an uninitialized instance variable of type String?
For reference types including String, uninitialized instance variables default to null. This is different from primitives which get type-specific defaults (0, false, etc.). A field declared as private String name; has value null until explicitly assigned. Note: null is not the same as empty string ("") — null means "no object reference", while empty string is an actual String object with zero characters. Be aware that calling methods on a null reference throws NullPointerException — always handle null possibility for reference type fields.

13. What is the difference between a local variable and a method parameter?
Local variables are declared inside the method body and must be initialized before use; they have method scope. Method parameters (arguments) are declared in the method signature and receive values from the caller at invocation; they are initialized by the caller. Both are stored on the stack, but parameters are initialized on method entry, while locals must be explicitly assigned. Parameters cannot be reassigned in a way that affects the caller (Java is pass-by-value), while local variables can be reassigned freely. Both local variables and parameters are not visible outside the method.

14. Can a final variable hold a mutable object?
Yes. final prevents reassigning the reference, but the referenced list can still change: final List<String> names = new ArrayList<>(); names.add("Ada"); is valid. For an unmodifiable list, use List.of("Ada") (Java 9+) or wrap a defensive copy with Collections.unmodifiableList. An unmodifiable wrapper alone does not protect its backing list from mutation through another reference.
15. What is the scope of a variable declared inside an if block?
A variable declared inside an if block (or any block { }) has block scope — it is only visible and usable within that block. After the block ends (the closing brace), the variable is out of scope and (if primitive) eligible for GC. This is narrower than method scope. Variables in nested blocks can shadow outer variables with the same name. Example: if (condition) { int count = 5; ... } // count not accessible here. To use a block-scoped variable outside the block, assign it to a variable declared before the block (which may have its own initialization requirements — the variable must be definitely assigned before use).

16. What is the effect of `static final` on a reference type?
static final on a reference type means the reference is constant — it can never be reassigned to point to a different object. However, the object itself is not protected from modification unless it's immutable. Example: static final List<String> CONFIG = new ArrayList<>(); — CONFIG always points to the same ArrayList, but you can still call CONFIG.add("x"). To create a truly immutable collection, use: static final List<String> CONFIG = List.of("x", "y"); (Java 9+) or static final List<String> CONFIG = Collections.unmodifiableList(List.of("x", "y"));. The choice matters for thread safety and defensive programming.

17. What is the difference between compile-time constant and runtime constant?
A constant variable is a final primitive or String initialized with a constant expression, as defined by the JLS. A compiler can embed its value in client bytecode. A field declared static final with a non-constant initializer is not a constant variable; it is initialized at runtime, and if it refers to a mutable object, that object's state can still change.
18. Can method parameters be final?
Yes — you can declare method parameters as final: void process(final int count, final String name). This prevents reassignment to the parameter inside the method body. This is useful as documentation and for preventing accidental modification, especially in long methods or when the parameter is used in inner classes/lambdas. For inner classes and lambdas, effectively final or explicitly final variables from the enclosing scope can be captured. Note: marking a parameter final does not affect the caller — the caller passes a value, and inside the method the parameter acts like a local variable that cannot be reassigned.

19. What is definite assignment?
Definite assignment is a Java rule ensuring that local variables are definitely assigned before use. The compiler performs flow analysis to verify that every path to a variable use assigns the variable. If a variable might be used without being assigned on some path, the compiler errors: "variable might not have been initialized". This rule applies to local variables and parameters (for blank final), but not to instance/static fields which have default values. Understanding definite assignment helps you write code where initialization is clear and the compiler can catch potential bugs before runtime.

20. What is the difference between final, finally, and finalize()?
final is a modifier meaning "cannot be changed" — applies to variables (reassignment prevented), methods (cannot be overridden), and classes (cannot be extended). finally is a block in try-catch-finally that always executes after try/catch, used for cleanup like closing resources. finalize() is a deprecated Object method called by garbage collector before reclaiming memory — it is not a substitute for proper resource cleanup and should not be relied upon. Effective Java recommends avoiding all three: use final for immutable references, try-with-resources for cleanup, and proper close() methods instead of finalize().

Further Reading

Conclusion

Java variables can have explicit types or use local inference with var (Java 10+). final prevents reassignment; it does not freeze an object. The distinction matters most with fields and collections, where a final reference can still point to mutable state.

Use var when the initializer makes the inferred type clear. A static final field is a JLS constant variable only when it has primitive or String type and a constant-expression initializer; other static final fields can still refer to mutable objects. List.of creates an unmodifiable list (Java 9+); an unmodifiable wrapper is only a view unless its backing list is also protected.

The distinction between primitives and reference types determines default values and behavior. For understanding how String (a reference type) behaves as an immutable sequence of characters, see The String Class, which covers concatenation, interning, and the String Pool.

Category

Related Posts

Abstract Classes in Java: Interfaces and Composition

Compare Java interfaces, abstract classes, and composition, then see when shared state, default methods, or sealed types change the design choice.

#java-abstract-classes #java #java-fundamentals

Arithmetic Operators in Java: Division, Overflow, Promotion

Compare Java arithmetic with runnable examples of division, negative remainders, overflow, type promotion, and BigDecimal for decimal money.

#java-arithmetic-operators #java #java-fundamentals

Java Array Basics: Length, Bounds, Copies, and Resizing

Learn Java arrays through runtime-sized allocation, bounds checks, aliasing, copying, and the fixed length that distinguishes them from ArrayList.

#java-array-basics #java #java-fundamentals