JAVA BASICS IN DETAIL

Java final keyword

final keyword ( final keyword) restricts later changes. For a variable it prevents reassignment, for a method it prevents overriding, and for a class it prevents inheritance.

Three main uses

What Java final means in different contexts
Where is it written?What does it restrict?What does it not do?
On a variableThe value or reference can be assigned only onceDoes not always make the referenced object immutable
On a methodA subclass cannot override the methodDoes not prevent inheritance or calls to the method
On a classAnother class cannot extend it using extendsDoes not prevent creating instances of the class

1. final variable is assigned once

Working example

final int MINIMALUS_AMZIUS = 18;

System.out.println(MINIMALUS_AMZIUS);
Console output

18

  1. To the variable MINIMALUS_AMZIUS we first assign 18.
  2. This value can be read and used in calculations.
  3. final does not mean the value must be known at compile time: it simply must be assigned only once.

Non-compiling example

final int MINIMALUS_AMZIUS = 18;

MINIMALUS_AMZIUS = 21; // Error: a second assignment is not allowed
Result

The code does not compile. The incorrect line remains active, and its trailing comment explains the reason: final variable has already been assigned a value.

A value can be assigned in the constructor

A class's final field can be declared without a value and assigned in each constructor. This is called a blank final field ( blank final field).

class Uzsakymas {
    final int numeris;
    String pirkejas;

    Uzsakymas(int numeris, String pirkejas) {
        this.numeris = numeris;
        this.pirkejas = pirkejas;
    }
}

Uzsakymas uzsakymas = new Uzsakymas(1042, "Ieva");
System.out.println(uzsakymas.numeris);
System.out.println(uzsakymas.pirkejas);
Console output

1042
Ieva

Each Uzsakymas object can have a different number, but an existing object's number cannot be reassigned.

class Uzsakymas {
    final int numeris;

    Uzsakymas() {
        // Error: numeris has not been assigned a value
    }
}
Result

The code does not compile. Every constructor path must assign the final field exactly once.

final reference does not mean an immutable object

Working example: changing object contents

final StringBuilder tekstas = new StringBuilder("Pirkinių sąrašas");

tekstas.append(": duona, pienas");
System.out.println(tekstas);
Console output

Pirkinių sąrašas: duona, pienas

  1. final locks the reference tekstas to one StringBuilder object.
  2. The StringBuilder itself is mutable, so its contents can be extended with append().

Non-compiling example: redirecting a reference

final StringBuilder tekstas = new StringBuilder("Pirkinių sąrašas");

tekstas = new StringBuilder("Kitas sąrašas"); // Error: second assignment
Result

The code does not compile. Instead of changing the old object's state, the code tries to redirect the variable tekstas to a different object.

An important distinction

final reference and an immutable ( immutable) object are not the same. Immutability also requires appropriate class design.

More about mutable and immutable objects

static final – a shared class constant

class Laikas {
    static final int MINUCIU_PER_VALANDA = 60;
    static final int SEKUNDZIU_PER_MINUTE;

    static {
        SEKUNDZIU_PER_MINUTE = 60;
    }
}

int sekundziu = 2
    * Laikas.MINUCIU_PER_VALANDA
    * Laikas.SEKUNDZIU_PER_MINUTE;

System.out.println(sekundziu);
Console output

7200

  1. static means the entire class shares one value.
  2. final prevents assigning it a second time.
  3. The value can be assigned immediately or in a static initializer block.
  4. Constant names conventionally use UPPER_SNAKE_CASE style.

More about Java constants

final method parameters and local variables

Working example

class Pasisveikinimas {
    static String sukurti(final String vardas) {
        return "Labas, " + vardas + "!";
    }
}

System.out.println(Pasisveikinimas.sukurti("Rūta"));
Console output

Labas, Rūta!

final parameter cannot be reassigned inside the method. This can express the intention not to change it, but an object parameter's internal state can still change if its class allows it.

Non-compiling example

class Pasisveikinimas {
    static String sukurti(final String vardas) {
        vardas = "Kitas vardas"; // Error: a final parameter cannot be changed
        return "Labas, " + vardas + "!";
    }
}
Result

The code does not compile because the method tries to assign the parameter vardas a different string.

2. final method cannot be overridden

class Mokestis {
    final double galutineKaina(double kaina) {
        return kaina * 1.21;
    }
}

class SpecialusMokestis extends Mokestis {
    double galutineKaina(double kaina) { // Error: a final method cannot be overridden
        return kaina;
    }
}
Result

The code does not compile because galutineKaina(double) is marked final.

final method is used when subclasses must not change an important rule or algorithm. They still inherit and can call the method:

class Mokestis {
    final double galutineKaina(double kaina) {
        return kaina * 1.21;
    }
}

class PvmMokestis extends Mokestis {
    void rodyti(double kaina) {
        System.out.println(galutineKaina(kaina));
    }
}

PvmMokestis mokestis = new PvmMokestis();
mokestis.rodyti(100);
Console output

121.0

More about Java method overriding

3. final class cannot be extended

final class AsmensKodas {
    private final String reiksme;

    AsmensKodas(String reiksme) {
        this.reiksme = reiksme;
    }

    String gauti() {
        return reiksme;
    }
}

class SpecialusKodas extends AsmensKodas { // Error: a final class cannot be extended
    SpecialusKodas(String reiksme) {
        super(reiksme);
    }
}
Result

The code does not compile because SpecialusKodas tries to extend final class a AsmensKodas.

final class ends the inheritance chain. This is useful when subclassing cannot safely change its behavior or its immutability rules require a fully controlled structure.

An example from Java

String is final class. Another class cannot extend it and change string behavior.

What does final not guarantee?

  • final reference does not guarantee an immutable object.
  • final class alone does not guarantee immutability: its fields can still change.
  • final does not automatically make code thread-safe.
  • final is not an access modifier and does not determine who can see a member.
  • final and finally are different Java keywords with different purposes.

When should you use it?

Choosing final in practice
SituationSolution
A value or reference must not change after assignmentfinal variable
A shared class constantstatic final field
Subclasses may inherit the method but cannot change its rulefinal method
A class must have no subclassesfinal class
An object must be fully immutableUsing final alone is insufficient: an immutable class design is needed

What should you remember?

  • final allows a variable to be assigned only once.
  • A blank final field must be initialized in every constructor.
  • final reference cannot point to another object, but the object itself can remain mutable.
  • final method cannot be overridden, but can be inherited and called.
  • final class cannot be extended.
  • static final is most often used for shared class constants.