Sobes.tech
Middle

What is the purpose of the 'final' keyword in Java (for fields, classes)?.

sobes.tech AI

Answer from AI

In Java, the keyword final is used to denote immutability:

  • final field — the value of the field cannot be changed after initialization. If the field is primitive, its value is fixed; if it is an object, the reference to the object cannot be reassigned, but the object itself can be modified (if it is mutable).

  • final class — the class cannot be inherited, meaning you cannot create a subclass from this class.

Example:

final class Constants {
    public static final double PI = 3.14159;
}

class Example {
    final int x = 10;

    void method() {
        // x = 20; // Compilation error — cannot modify a final field
    }
}

Using final helps improve code safety by preventing unwanted modifications and inheritance.