Java Final Keyword – A Complete Guide with Examples

Introduction

In Java, the final keyword is a non-access modifier that can be applied to variables, methods, and classes. It is used to impose restrictions and ensure certain values, behaviors, or structures remain unchanged during program execution.

In simple words:

  • Final variable → Constant value (cannot be changed once assigned).
  • Final method → Cannot be overridden.
  • Final class → Cannot be inherited.

This makes final a very powerful tool in ensuring immutability, security, and proper design in Java applications.

1. Final Variables in Java

When a variable is declared as final, its value cannot be changed once assigned.

Syntax:

final double INTEREST_RATE = 0.05;

Example: Final Variable

In banking, the interest rate is usually fixed and should not change once set.

class BankAccount {
    private String accountHolder;
    private double balance;
    final double INTEREST_RATE = 0.05;  // 5% fixed interest rate

    BankAccount(String holder, double amount) {
        this.accountHolder = holder;
        this.balance = amount;
    }

    void calculateInterest() {
        double interest = balance * INTEREST_RATE;
        System.out.println("Interest for " + accountHolder + " is: " + interest);
    }
}

public class FinalVariableRealExample {
    public static void main(String[] args) {
        BankAccount acc1 = new BankAccount("Alice", 10000);
        acc1.calculateInterest();
    }
}

Key Points:

  • A final variable must be initialized at the time of declaration or inside a constructor.
  • Once assigned, its value cannot be modified.
  • Commonly used for constants (e.g., PI, MAX_VALUE).

2. Final Methods in Java

When a method is declared as final, it cannot be overridden by subclasses.

Example: Final Method

class Vehicle {
    final void startEngine() {
        System.out.println("Engine started");
    }
}

class Car extends Vehicle {
    // ❌ This will cause an error
    // void startEngine() {  
    //     System.out.println("Car engine started");
    // }
}

public class FinalMethodExample {
    public static void main(String[] args) {
        Car car = new Car();
        car.startEngine();
    }
}

Why use Final Methods?

  • To prevent subclasses from changing critical methods.
  • Ensures consistent behavior across inheritance hierarchy.

3. Final Classes in Java

When a class is declared as final, it cannot be extended (inherited).

Example: Final Class

final class Bank {
    void displayBankName() {
        System.out.println("Welcome to XYZ Bank");
    }
}

// ❌ Compile-time error: Cannot inherit from final class
// class MyBank extends Bank { }

public class FinalClassExample {
    public static void main(String[] args) {
        Bank bank = new Bank();
        bank.displayBankName();
    }
}

Why use Final Classes?

  • To prevent inheritance for security or design reasons.
  • Commonly used in classes like java.lang.String, java.lang.Math, and java.lang.System.

4. Final Parameters in Java

You can also declare method parameters as final. This ensures that the parameter’s value cannot be modified inside the method.

Example: Final Parameter

public class FinalParameterExample {
    void calculateSquare(final int number) {
        // number = number * number;  // ❌ Error: cannot assign a value to final variable
        System.out.println("Square: " + (number * number));
    }

    public static void main(String[] args) {
        FinalParameterExample obj = new FinalParameterExample();
        obj.calculateSquare(5);
    }
}

5. Blank Final Variable (Uninitialized Final Variable)

A final variable that is not initialized at declaration time is called a blank final variable.
It must be initialized in the constructor.

Example:

class Student {
    final int rollNumber;  // blank final variable

    Student(int roll) {
        rollNumber = roll;  // initialized in constructor
    }

    void display() {
        System.out.println("Roll Number: " + rollNumber);
    }
}

public class BlankFinalExample {
    public static void main(String[] args) {
        Student s1 = new Student(101);
        Student s2 = new Student(102);

        s1.display();
        s2.display();
    }
}

6. Static Final Variables (Constants)

A static final variable is used to define constants (commonly written in uppercase).

Example:

class Constants {
    static final double PI = 3.14159;
    static final int MAX_USERS = 100;
}

public class StaticFinalExample {
    public static void main(String[] args) {
        System.out.println("PI: " + Constants.PI);
        System.out.println("Max Users: " + Constants.MAX_USERS);
    }
}

7. Final with Inheritance and Polymorphism

  • Final variable → value cannot change.
  • Final method → cannot override, but can be inherited.
  • Final class → cannot be subclassed at all.

This provides control and security in object-oriented design.

8. Real-world Use Cases of Final Keyword

  1. Constants definition: public static final String COMPANY_NAME = "Google";
  2. Immutable classes: The String class is final to prevent modification.
  3. Preventing override: Security-sensitive methods (e.g., Object.wait(), Object.notify()).
  4. Performance optimization: JVM can optimize final classes and methods better.

🎯Conclusion

The final keyword in Java is a simple yet powerful tool to restrict modification, inheritance, and overriding.

  • Use it for constants (final variables).
  • Secure critical methods (final methods).
  • Prevent unwanted inheritance (final classes).

By understanding and using final effectively, you can write more secure, maintainable, and efficient Java programs.

Backend developer working with Java, Spring Boot, Microservices, NoSQL, and AWS. I love sharing knowledge, practical tips, and clean code practices to help others build scalable applications.

Leave a Reply

Your email address will not be published. Required fields are marked *