CodeBlanks Logo Icon CodeBlanks

final field guarantees

Learn initialization guarantees of final fields.

The guarantee of final fields

A final field is assigned exactly once, in the constructor, and never changes after. The Java Memory Model guarantees that when the constructor completes, the field is visible to all threads; this is called safe publication.

Example: final int x. When an object is published, another thread reading x sees the value assigned in the constructor; there is no risk of seeing a half-constructed object. So immutable objects are designed with final fields; this is both safe and efficient for the garbage collector.

Immutable objects

An object whose fields are all final and whose methods do not change state is immutable. Immutable objects are thread-safe because their state never changes after publication.

Example: class Point { final int x; final int y; }. Once a Point is created, x and y stay constant, so it can be shared without locking. Java's String and LocalDate are immutable, which lets them be cached and shared safely.

Practice An immutable Point class

Define a Point class with final int x and final int y fields; a Point(int x, int y) constructor assigns them. In main, create new Point(3, 4) and print p.x + p.y with System.out.println.

Starter code

Main.java
// Define the Point class
// Add final x and y fields
// Print the sum in main

Sample solution

Main.java
class Point {
    final int x;
    final int y;
    public Point(int x, int y) { this.x = x; this.y = y; }
}

public class FinalDemo {
    public static void main(String[] args) {
        Point p = new Point(3, 4);
        System.out.println(p.x + p.y);
    }
}

Expected output

7

Questions and answers

Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.

1 What visibility does a final field guarantee?

  • Variable visibility
  • A single instance
  • Post-constructor visibility Correct answer
  • Stack placement

Explanation: A final field becomes visible when the constructor finishes.

2 Declare a final field

Question
public ____ int x;
Answer
public final int x;

Explanation: A final field is assigned only in the constructor.

3 Match the final field concepts

Term Meaning
final field Visible after constructor
volatile Visibility
synchronized Locking
local variable On the stack

All lessons in Expert