Java Variables and Constants
Understand Java variables, Java 10 local type inference, final references, and the rules for compile-time constants and static fields.
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
Stringtype - Configuration values that never change
- Singleton pattern implementations
Avoid overusing:
varwhen type is not immediately clear (harms readability)finalon parameters when not needed (adds noise)static finalfor 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:
finalprevents 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; }
}
-
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; -
Var with non-obvious type
// BAD - what is the type? var result = getDataFromService(); // GOOD - type is clear List<Transaction> result = getDataFromService(); -
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"); -
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
-
finalprevents reassignment but doesn’t make objects immutable -
varinfers type at compile time — works only for local variables - A
static finalfield 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
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.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.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.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.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.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.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.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.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.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.{ }) 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).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.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.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.Further Reading
- Fields and Instance Variables — Field declarations and defaults
- Encapsulation in Java — Controlling access to mutable state
- The String Class — String immutability and the String pool
- Java Enums — When a fixed set of named values should be a type
- JLS §4.12.4:
finalVariables - JLS §15.29: Constant Expressions
- JEP 286: Local-Variable Type Inference —
varwas added in Java 10
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.
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 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.