Chapter 35 of 77

final Keyword in Java

In the Constants chapter, we used final to create values that should never change, such as final double PI = 3.14159;. Since then, we have learned about classes, objects, constructors, this, and static. Now we can see that final can do much more than create constants.

The word final means "this is the last version, no more changes". Java lets us use it in three places:

final variable → its value can be assigned only once
final method   → it cannot be overridden by a child class
final class    → it cannot be extended (no child classes)

In this chapter, we will look at each of these, and also clear up one very common confusion: a final reference does not make the object itself unchangeable.

final Variables

A final variable can be assigned a value only once. After that, it cannot be reassigned.

You have already seen this with local variables:

final int DAYS_IN_WEEK = 7;

DAYS_IN_WEEK = 8; // Error

The compiler stops us with this error:

error: cannot assign a value to final variable DAYS_IN_WEEK

A final local variable does not have to get its value on the same line. It just has to be assigned exactly once before it is used:

final int discount;

if (isMember) {
    discount = 20;
} else {
    discount = 5;
}

System.out.println(discount); // works: discount was assigned exactly once

Java checks every possible path through the code. Here, whichever branch runs, discount is assigned only once, so the code compiles.

final Instance Variables

We can also make a field of a class final. This is very useful for values that are decided when an object is created and should never change afterwards, such as a roll number, an account number, or a date of birth.

A final field without a value is called a blank final. It must be assigned in the constructor:

class Student {
    final int rollNumber;
    String name;

    Student(int rollNumber, String name) {
        this.rollNumber = rollNumber;
        this.name = name;
    }
}

class Main {
    public static void main(String[] args) {

        Student s1 = new Student(101, "Aman");
        Student s2 = new Student(102, "Priya");

        s1.name = "Aman Verma"; // allowed, name is not final
        // s1.rollNumber = 999; // Error: rollNumber is final

        System.out.println(s1.rollNumber + " " + s1.name);
        System.out.println(s2.rollNumber + " " + s2.name);
    }
}

Output:

101 Aman Verma
102 Priya

Notice two things:

  • Each object gets its own rollNumber (101 and 102). final does not mean "shared"; that is what static means.

  • Once the constructor has set rollNumber, nobody can change it, not even a method of the same class.

If we forget to assign a final field, the code will not compile. For example, a constructor that never sets rollNumber gives:

error: variable rollNumber might not have been initialized

So a final field must be assigned exactly once, either where it is declared or in every constructor.

static final: Class-Level Constants

When a value is the same for every object and should never change, we combine static and final:

  • static → one copy, belonging to the class

  • final → cannot be reassigned

This is how real constants are written in Java classes:

class AppConfig {
    static final int MAX_LOGIN_ATTEMPTS = 3;
    static final double GST_RATE = 0.18;
    static final String APP_NAME = "CS Learning Portal";
}

class Main {
    public static void main(String[] args) {

        System.out.println(AppConfig.APP_NAME);
        System.out.println("Max attempts: " + AppConfig.MAX_LOGIN_ATTEMPTS);

        double price = 1000;
        double total = price + price * AppConfig.GST_RATE;
        System.out.println("Total with GST: " + total);

        System.out.println(Math.PI);
        System.out.println(Integer.MAX_VALUE);
    }
}

Output:

CS Learning Portal
Max attempts: 3
Total with GST: 1180.0
3.141592653589793
2147483647

Java's own library uses the same idea. Math.PI and Integer.MAX_VALUE are both public static final fields, which is why we can use them with the class name and can never change them.

By convention, static final constants are written in UPPER_SNAKE_CASE, just as we learned in the Constants chapter.

final Reference vs Unchangeable Object

This is the part that confuses many beginners (and is a favourite interview question).

When a final variable holds an object (or an array), it is the reference that becomes final, not the object. The variable must always point to the same object, but the object's contents can still change.

import java.util.Arrays;

class Main {
    public static void main(String[] args) {

        final StringBuilder message = new StringBuilder("Hello");
        message.append(" World");      // allowed: changing the object
        System.out.println(message);

        final int[] marks = {70, 80, 90};
        marks[0] = 75;                 // allowed: changing an element
        System.out.println(Arrays.toString(marks));

        // message = new StringBuilder("Bye"); // Error: cannot point to a new object
        // marks = new int[5];                 // Error: cannot point to a new array
    }
}

Output:

Hello World
[75, 80, 90]

Think of it like this:

final StringBuilder message
        │
        │  (this arrow can never move)
        ▼
  [ "Hello World" ]   ← but what is inside the box can change

If you want an object whose contents can never change, you need an immutable class, such as String. Every method on a String that looks like it changes the text actually returns a new String instead. final on the variable alone is not enough.

final fixes the reference, not the object it points to.

final Parameters

Method parameters can also be marked final. This means the method cannot assign a new value to that parameter:

static int square(final int x) {
    x = x * x;   // Error
    return x;
}
error: final parameter x may not be assigned

The correct version uses a new variable:

static int square(final int x) {
    int result = x * x;
    return result;
}

final parameters are optional. Some teams use them to make it clear that a parameter is only read, never changed, inside the method.

final Methods

In the upcoming Inheritance chapter, you will learn that one class can extend another class and reuse its code. A child class can also override (replace) a parent's method with its own version. You will learn both of these properly in the next few chapters; for now, just know that final can block them.

A final method cannot be overridden by a child class:

class Parent {
    final void show() {
        System.out.println("Parent's show");
    }
}

class Child extends Parent {
    void show() {   // Error
        System.out.println("Child's show");
    }
}
error: show() in Child cannot override show() in Parent
  overridden method is final

The child class can still call the final method; it just cannot replace it. We make a method final when its behaviour is important and must stay exactly the same in every child class, for example a method that checks a password or calculates a bank balance.

final Classes

A final class cannot be extended at all:

final class Parent {
}

class Child extends Parent {  // Error
}
error: cannot inherit from final Parent

You have already used a famous final class: String. If you try to write class MyString extends String, Java gives error: cannot inherit from final String. This keeps String safe: nobody can create a "fake" String subclass that behaves differently. The wrapper classes such as Integer and Double are also final.

Note that a final class can still have normal, changeable fields. final on a class only stops inheritance; it does not make the objects immutable.

A Complete Example

Let's use the different kinds of final together in one class:

class BankAccount {
    static final double MIN_BALANCE = 500.0;   // one shared constant

    final String accountNumber;                // set once per object
    double balance;                            // can change

    BankAccount(String accountNumber, double balance) {
        this.accountNumber = accountNumber;
        this.balance = balance;
    }

    final void withdraw(final double amount) {
        if (balance - amount < MIN_BALANCE) {
            System.out.println("Withdrawal of " + amount + " denied for " + accountNumber);
            return;
        }
        balance = balance - amount;
        System.out.println("Withdrew " + amount + ", balance: " + balance);
    }
}

class Main {
    public static void main(String[] args) {

        BankAccount account = new BankAccount("SB-1001", 2000.0);

        account.withdraw(1000.0);
        account.withdraw(800.0);

        System.out.println("Account: " + account.accountNumber);
        System.out.println("Minimum balance: " + BankAccount.MIN_BALANCE);
    }
}

Output:

Withdrew 1000.0, balance: 1000.0
Withdrawal of 800.0 denied for SB-1001
Account: SB-1001
Minimum balance: 500.0

Here:

  • MIN_BALANCE is a static final constant shared by all accounts.

  • accountNumber is a blank final field, set once in the constructor.

  • balance is a normal field, because it must change.

  • withdraw() is a final method, so a child class could never replace the withdrawal rules, and its parameter amount cannot be reassigned inside it.

Summary Table

Used on

Meaning

Example

Local variable

Can be assigned only once

final int max = 10;

Instance variable

Set once per object (at declaration or in every constructor)

final int rollNumber;

static variable

One shared constant for the class

static final double PI = 3.14159;

Parameter

Cannot be reassigned inside the method

void pay(final double amount)

Method

Cannot be overridden

final void withdraw()

Class

Cannot be extended

final class String

Common Mistakes

  • Thinking final makes an object immutable. A final StringBuilder or a final int[] can still have their contents changed. Only the variable is locked.

  • Confusing final with static. final means "cannot be reassigned"; static means "belongs to the class". A final instance field still has a separate copy in every object.

  • Forgetting to assign a blank final in one of the constructors. If a class has two constructors, both must assign every final field.

  • Trying to change a final field in a setter method. A final field can only be assigned during object creation, so a setter like setRollNumber() will not compile.

Interview Corner: final vs finally vs finalize

These three words look alike but are completely unrelated:

  • final is a keyword used on variables, methods, and classes, as explained in this chapter.

  • finally is a block used with try-catch that normally runs whether or not an exception happens. You will meet it in the Exception Handling chapter.

  • finalize() is an old method of the Object class that was meant to run before the garbage collector removed an object. It was unreliable, was deprecated in Java 9, and has been marked for removal since Java 18. You should not use it in new code.

The Main Idea

Use final whenever something should not change after it is set. It protects your code from accidental changes and makes your intention clear to anyone reading it.

final variable → assign once. final method → cannot override. final class → cannot extend.

And always remember that for objects, final locks the reference, not the contents of the object.