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.0final 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
Related recipes
In the tutorial
- Variables — Declaring variables in Java: type and name, assignment, var, final constants and naming rules.