Back to Intellij Community

FieldMayBeFinal

java/java-impl/resources/inspectionDescriptions/FieldMayBeFinal.html

2025.3-rc-21.1 KB
Original Source

Reports fields that can be safely made final. All final fields have a value and this value does not change, which can make the code easier to reason about.

To avoid too expensive analysis, this inspection only reports if the field has a private modifier or it is defined in a local or anonymous class. A field can be final if:

  • It is static and initialized once in its declaration or in one static initializer.
  • It is non-static and initialized once in its declaration, in one instance initializer or in every constructor

And it is not modified anywhere else.

Example:

public class Person {
    private String name; // can be final

    Person(String name) {
      this.name = name;
    }

    public String getName() {
      return name;
    }
  }

After the quick-fix is applied:

public class Person {
    private final String name;

    Person(String name) {
      this.name = name;
    }

    public String getName() {
      return name;
    }
  }

Use the "Annotations" button to modify the list of annotations that assume implicit field write.