Encodera

Thanks for reading!

Donate to the site — we work hard for you.

Java reference

final

Forbids reassigning a variable, overriding a method or extending a class.

Available since: Java 1.0

Syntax

final Type name = value;

Examples

A constant — a static final field with an upper-case name:

static final double VAT_RATE = 0.2;
 
void main() {
    final int price = 100;
    // price = 200;  // error: cannot assign a value to final variable price
    IO.println(price * (1 + VAT_RATE));
}

Output:

120.0

final forbids reassigning the reference, not changing the object:

void main() {
    final List<String> names = new ArrayList<>();
    names.add("Anna");
    names.add("Oleg");
    IO.println(names);
}

Output:

[Anna, Oleg]

Notes

final has three meanings: on a variable it cannot be reassigned, on a method it cannot be overridden in a subclass, on a class it cannot be extended (this is how String is declared).

To make the list itself unchangeable you need an immutable collection such as List.of(...). Variables used inside lambdas must be final or "effectively final" — not changed after assignment.

See also

  • static — Makes a field or method belong to the class itself rather than to each object.
  • var — Declares a local variable whose type the compiler infers from the value.
  • record — Declares a record — an immutable data class with ready-made equals(), hashCode() and toString().

Related recipes

In the tutorial

  • Variables — Declaring variables in Java: type and name, assignment, var, final constants and naming rules.

Thanks for reading!

Donate to the site — we work hard for you.