skip to content

Initialization

The precise order in which static and instance initializers, field initializers and constructors run, plus the rules for final fields. Output-prediction questions in this area are an interview staple.

part ofJavaread it →
on this pageshow

explore

questions

10

What are the rules for initializing a final field in Java, and what does 'definitely assigned exactly once' mean?

level: juniorimportance: must knowfreq 70%

answer

  1. Assign once; no second assignment
  2. Three spots: declaration, instance block, constructors
  3. Compiler proves it via definite-assignment analysis
  4. final reference vs final object contents

basics

~20 s

A Java final field must be assigned exactly once, and ordinary code cannot reassign it afterward. An instance final is set at its declaration, in an instance block, or by constructors. Leaving it unset or assigning it twice will not compile.

solid answer

~50 s

A `final` field is one the language lets you assign only once. 'Definitely assigned exactly once' is shorthand for two compile-time rules: for a blank final instance field, by the end of every constructor, on each path that completes normally, the field must be **definitely assigned**, and before each assignment it must be **definitely unassigned**. So an instance final is set at its declaration, in an instance initializer block, or by the constructors, and the compiler rejects leaving it unset or possibly assigning it twice. It also rejects reading an unassigned final by simple name or `this.x`, though a method called during construction can still see the default value. One limit: deep reflection can change a final instance field, with a warning by default since JDK 26 and silently on JDK 25. `final` fixes the variable, not the object it refers to, and differs from `final` on a method or class.

go deeper

for a junior

Knows a final field is set once and ordinary code cannot reassign it, and can name the declaration vs constructor assignment options.

for a middle

Explains 'definitely assigned exactly once', distinguishes final reference from final object contents, and knows the three assignment locations.

for a senior

Discusses compiler definite-assignment analysis across branches and ties final fields to immutability and safe construction.

for a principal

Relates final-field semantics to the Java Memory Model's safe-publication guarantees and to immutable-object design as an API/concurrency strategy.

## What 'final' means on a field In Java, the keyword **final** applied to a field (a variable that belongs to an object or class) means the field can be **assigned a value only once**. After that single assignment, any further assignment in source code is a **compile-time error**: the program will not compile. A **field** is a variable declared inside a class but outside any method, e.g. `private final int x;`. An **instance field** belongs to each object; a **static field** belongs to the class itself. ## 'Definitely assigned exactly once' The phrase is shorthand for two rules the Java Language Specification applies to a **blank final** instance field, a `final` instance field declared without a value: - **Definitely assigned**: at the end of *every* constructor, on every path that completes normally, the field has been given a value. The compiler performs *definite-assignment analysis*: it traces all branches (if/else, switch, loops, try/catch) and proves the field is set on each one. If even one path could leave it unset, compilation fails. A path that ends by throwing an exception never finishes construction, so it owes nothing. - **Definitely unassigned before each assignment**: no path may reach an assignment with the field possibly already set, including a second trip round a loop. This is the 'exactly once' half. A `final` field that has an initializer is simpler: any later assignment to it is rejected. The same analysis also rejects reading a blank final by its simple name or as `this.x` before it is definitely assigned. ## Where you may assign it There are exactly three legal places to assign a `final` instance field: 1. **At the declaration (field initializer):** ```java private final int size = 10; ``` 2. **In an instance initializer block** (a `{ ... }` block in the class body that runs right after the superclass constructor returns): ```java class Sized { private final int size; { size = 10; } } ``` 3. **In a constructor**: then every constructor must leave it assigned, on every path that completes normally, directly or by delegating with `this(...)` (this is the 'blank final' case, covered separately). A `final` field is assigned in **one** of these mechanisms, not several. For example, if you give it a value at the declaration, you cannot also assign it in a constructor. A `static final` field follows the same idea at class level: it is assigned at its declaration or in a static initializer block, never in a constructor. ## Why the rule exists The point is **immutability**: ordinary code cannot reassign a `final` field once it is set. This makes the value safe to read repeatedly, easier to reason about, and (under the Java Memory Model) safely visible to other threads after construction. The compiler's analysis means no constructor path can forget the assignment or repeat it. ## What it does NOT mean - `final` makes the **reference/variable** unchangeable, not the **object it points to**. `final List<String> list = new ArrayList<>();` still lets you call `list.add(...)`: the list contents are mutable; you just can't repoint `list`. - `final` on a field is unrelated to `final` on a method (can't be overridden) or `final` on a class (can't be extended). - `final` does not hide the **default value**. The compiler follows names, not calls, so a method called during construction reads whatever the field holds at that moment: ```java class Peek { final int x; Peek() { System.out.println(read()); // prints 0 x = 3; } int read() { return x; } } ``` ## The limit: deep reflection The Java Language Specification says final fields "can be changed via reflection and other implementation-dependent means". The route is `Field.setAccessible(true)` followed by `Field.set`, and what happens to a final instance field of an ordinary class depends on the release: | Release and options | Write through `Field.set` | |---|---| | JDK 5 up to JDK 25 LTS | Succeeds silently, once `setAccessible(true)` has succeeded | | JDK 26 and 27, default | Succeeds, with a warning at most once per module | | JDK 26 and 27, `--illegal-final-field-mutation=deny` | Throws `IllegalAccessException` | | JDK 26 and 27, `--enable-final-field-mutation=ALL-UNNAMED` | Succeeds without a warning for the code it names | JEP 500 says `deny` will become the default in a future release. Hidden classes since JDK 15 and record classes since JDK 16 refuse such a write whatever the flags (JEP 500), and on JDK 27 `Field.set` also refuses a `static final` field. ## A worked example ```java class Circle { private final double radius; // blank final private final double pi = 3.14159; // assigned at declaration Circle(double r) { radius = r; // assigned exactly once in the constructor } } ``` Here `pi` is set at its declaration; `radius` is a blank final set once in the constructor. Both are 'definitely assigned exactly once'.

  • Does final on a field make the object it points to immutable?
    No. final fixes the variable binding — you cannot reassign the field — but the object it references can still be mutated (e.g. adding to a final List). True immutability requires the referenced type to also be immutable.
  • Can a final field be left unassigned?
    No. A blank final instance field must be definitely assigned at the end of every constructor, on each path that completes normally, so a constructor that can finish without it assigned is a compile error. A constructor that delegates with this(...) or a path that throws owes nothing; a blank static final is assigned by a static initializer instead.
  • Can anything change a final field after construction?
    Deep reflection can: setAccessible(true) plus Field.set writes a final instance field. It is silent on JDK 25, warns by default on JDK 26 and 27, and JEP 500 plans to deny it by default later. A record's fields have refused it since JDK 16, and on JDK 27 a static final field refuses it too. A final initialized with a constant expression may not show the change, because uses were replaced at compile time.

  • Thinking final makes the referenced object immutable (it only fixes the variable)
  • Believing definite assignment is checked at run time; the compiler does it
  • Claiming you can assign a final field in any method, not just constructors/initializers
  • Believing the compiler stops all code from seeing a final field's default value

warning on final field mutation by deep reflection
Java 26

Assumes JDK 27. The language rules are the same on JDK 25 LTS; only deep reflection differs: writing a final instance field of an ordinary class through Field.set warns by default since JDK 26 and is silent on JDK 25.

context

open as a page

In Java, what is the difference between static initialization and instance initialization, and when does each one run?

level: juniorimportance: must knowfreq 70%

basics

~20 s

Static initializers (static fields and static blocks) run once, when the class is first loaded. Instance initializers (instance fields and instance blocks) run every time you create an object with new, just before the constructor body.

open as a page

What is a 'blank final' instance field in Java, and what must every constructor do for it?

level: middleimportance: must knowfreq 62%

basics

~20 s

A blank final is a final variable declared without a value, such as private final int id. As an instance field, it must be set exactly once by the end of every constructor: directly, through this(...), or in an instance initializer.

open as a page

Walk through the exact order of operations when you call new on a subclass: default values, super constructor, instance initializers, field initializers, and the constructor body. Why is this order important?

level: middleimportance: must knowfreq 68%

basics

~20 s

On new: fields first get default values (0/null/false), then the parent constructor runs fully, then this class's instance field initializers and instance blocks run top-to-bottom, and finally the constructor body runs. Parent is always fully built before the child.

open as a page

In Java, how do field initializers and instance initializer blocks interact when assigning final fields, and in what order do they run relative to the constructor?

level: seniorimportance: should knowfreq 40%

basics

~20 s

Field initializers and instance initializer blocks run in source order, right after the superclass constructor returns and before the statements following super(...). Since JDK 25, statements before super(...) run first. A final field is assigned only once across all of them.

open as a page

In Java, how does initializing a static final field differ from an instance final field, and what is a compile-time constant?

level: seniorimportance: should knowfreq 45%

basics

~20 s

A static final field is set once at class initialization, at its declaration or in a static block, never in a constructor. A compile-time constant is a final primitive or String with a constant-expression initializer, copied into using code.

open as a page

What initialization-order pitfalls can produce wrong values, NullPointerExceptions, or ExceptionInInitializerError, and how do you avoid them?

level: seniorimportance: should knowfreq 40%

basics

~20 s

Common traps: a static field reads another static field declared later (gets default value), a constructor calls an overridable method that sees uninitialized subclass fields, and an exception in a static initializer becomes an ExceptionInInitializerError that permanently breaks the class. Avoid by ordering declarations carefully and not calling overridable methods from constructors.

open as a page

How does static initialization run across a class hierarchy, and exactly when is a superclass's static initialization triggered relative to a subclass's?

level: seniorimportance: should knowfreq 45%

basics

~20 s

A class's static initialization runs once, and a superclass is always initialized before its subclass. So when a subclass is first used, the JVM initializes the parent's statics first, then the child's. Each happens at most once.

open as a page

How do final instance fields interact with the Java Memory Model to provide safe publication, and what design rule does this imply for immutable objects?

level: principalimportance: should knowfreq 30%

basics

~20 s

The Java Memory Model gives a special guarantee: if you set a final field during construction and don't let the object escape before the constructor finishes, any other thread that later sees the object is guaranteed to see the correctly initialized final field, even without locks or volatile.

open as a page

How does constructor chaining with this(...) interact with instance field initializers and instance blocks, and how many times do those initializers run?

level: middleimportance: nice to knowfreq 28%

basics

~20 s

When a constructor calls this(...) to delegate to another constructor of the same class, the instance field initializers and instance blocks run only once, in the constructor that actually calls super(...). Delegating constructors do not re-run them.

open as a page