Heart containing Coding Chica Java 101

Internal Changes Only! Java’s final Keyword for Fields

TIP: References Quick List

Table of Contents

  1. Table of Contents
  2. Introduction
  3. Reassignment
  4. Static Variables
    1. Allowed – Initial Assignment
  5. Disallowed – Reassignment
  6. Modifications In-Place
  7. 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.

Internal Changes Only! Java’s final Keyword for Fields

Leave a comment

This site uses Akismet to reduce spam. Learn how your comment data is processed.