Table of Contents
- Table of Contents
- Introduction
- Reassignment
- Static Variables
- Disallowed – Reassignment
- Modifications In-Place
- Summary
Introduction
In the last two posts, we talked about how primitives vs. objects are passed into methods as input parameters and how the final keyword impacts the ability to reassign the input parameter’s value. However, the final keyword does not prevent modifications of an object in-place. Similar behavior is seen when the final keyword is used on static or instance fields.
Reassignment
The final keyword on a static (class-level) or instance variable will prevent the reassignment of the variable to a new value.
- primitives: Prevents changing the value, as the value is stored directly.
- objects: Prevents reassigning the variable to a new object (address), as the value stored in the variable is a reference to the object elsewhere in memory.
The variable can receive an initial assignment, such as in a static block or in a constructor. However, after that, all subsequent re-assignment attempts will cause a compilation failure.
Static Variables
Allowed – Initial Assignment
private static final int MAX_COUNT = 10
private static final List<String> KEYWORDS = new ArrayList<>();
Disallowed – Reassignment
{
// Static code blocks and methods will not be able to reassign the value or object reference
// stored in the variable.
// The following will result in a compilation error.
KEYWORDS = new ArrayList<>();
}
public void setMaxCount(int count) {
// This will also result in a compilation failure due to the final keyword.
MAX_COUNT = count;
}
Modifications In-Place
However, any state-modifying methods that act upon the object in-place, such as the List’s add or clear methods, will still be allowed. For example:
private static final List<String> KEYWORDS = new ArrayList<>();
{
// Static code blocks and methods will not be able to reassign the value or object reference
// stored in the variable.
// The following will result in a compilation error.
KEYWORDS.add("ABC");
}
Summary
Just like when dealing with input parameters for a method, static (class level) or instance variables can take the final Java keyword to prevent reassignment, which prevents primitive value updates. However, adding the final keyword does not prevent internal state changes for an already-assigned object.

Leave a comment