final Keyword in Java: Variables, Methods, and Classes Explained with Examples

Illustration for final Keyword in Java: Variables, Methods, and Classes Explained with Examples
By Last updated:

The final keyword in Java is a powerful modifier used to create constants, prevent method overriding, and stop class inheritance. Understanding final is crucial for designing secure and immutable code.


📌 What is the final Keyword?

  • Definition: A non-access modifier that can be applied to variables, methods, and classes.
  • Why it matters: Ensures immutability, prevents accidental changes, and enforces design constraints.
  • When to use: When you want to create constants, restrict behavior, or maintain class integrity.

[Related: link-to-other-article]


🔹 final Variables

✅ Core Concept:

  • Once assigned, the value of a final variable cannot change.
  • Must be initialized at declaration or in a constructor.

💻 Example:

class Config {
    final int MAX_USERS = 100;
}

✅ Blank final Variables:

class Config {
    final int MAX_USERS;

    Config(int value) {
        this.MAX_USERS = value; // Initialized in constructor
    }
}

🔹 final Methods

✅ Core Concept:

  • A final method cannot be overridden by subclasses.

💻 Example:

class Parent {
    final void display() {
        System.out.println("Final method in Parent");
    }
}

class Child extends Parent {
    // void display() { } // Compilation error
}

🔹 final Classes

✅ Core Concept:

  • A final class cannot be inherited.

💻 Example:

final class Utility {
    static void show() {
        System.out.println("Utility method");
    }
}

// class ExtendedUtility extends Utility { } // Compilation error

🔹 Real-World Analogy

Think of final like a sealed envelope:

  • final variable: Once sealed, contents can’t be changed.
  • final method: You can’t alter the message inside.
  • final class: The envelope itself cannot be reused or modified.

📊 Comparison Table

Usage Effect
final variable Value cannot be changed
final method Cannot be overridden
final class Cannot be inherited

🚫 Common Mistakes and Anti-Patterns

  • ❌ Forgetting to initialize final variables.
  • ❌ Misusing final for performance; it does not guarantee optimization.
  • ❌ Declaring mutable objects as final thinking they are immutable (only reference is final).

📈 Performance and Memory Implications

  • final variables may allow compiler optimizations, but not guaranteed.
  • final helps JVM inline constants and methods for better performance in some cases.
  • No additional memory overhead; can reduce errors.

🔧 Best Practices

  • Use final for constants (public static final).
  • Mark methods final when overriding should be prevented.
  • Use final classes for utility or security-sensitive classes (e.g., String is final).

📚 Interview Questions

  1. Q: What is the difference between final, finally, and finalize()?
    A: final is a modifier, finally is a block in exception handling, finalize() is a method called by GC.

  2. Q: Can a constructor be final?
    A: No, constructors cannot be inherited, so final is meaningless.

  3. Q: Can we reassign a final reference variable?
    A: No, but the object it refers to can change its state.

  4. Q: Can final methods be overloaded?
    A: Yes, overloading is allowed; overriding is not.

  5. Q: Is declaring a variable final the same as making it static?
    A: No, static relates to class-level scope, final relates to immutability.

  6. Q: Can we declare abstract and final together?
    A: No, they are contradictory; abstract expects overriding, final prevents it.

  7. Q: Are final variables thread-safe?
    A: They are safe after initialization, but not inherently synchronized.

  8. Q: Can a final class implement interfaces?
    A: Yes, but no class can extend it.

  9. Q: Is String truly immutable because it’s final?
    A: String is final to prevent extension; immutability is due to internal design.

  10. Q: Does final improve performance always?
    A: Not necessarily; depends on JVM optimizations.


📌 Java Version Relevance

Java Version Change
Java 1.0 Introduced final keyword
Java 1.4+ JVM optimizations for final constants improved

✅ Conclusion & Key Takeaways

  • final enforces immutability and design constraints on variables, methods, and classes.
  • Use it for constants, preventing overriding, and secure utility classes.
  • Understand the difference between final, finally, and finalize().

❓ FAQ

Q1: Can we have a final static variable?
A: Yes, commonly used for constants.

Q2: Can we make local variables final?
A: Yes, often used in anonymous inner classes.

Q3: Are final arrays immutable?
A: No, only the reference is immutable.

Q4: Can we assign a final variable later?
A: Yes, if it’s a blank final variable initialized in a constructor.

Q5: Can an interface method be final?
A: No, all interface methods are implicitly abstract unless default or static.

Q6: Is it good to mark all variables final?
A: No, use only for constants or where immutability is required.

Q7: Can a final method be synchronized?
A: Yes, final and synchronized can be used together.

Q8: Can we remove final from String?
A: No, String is final by design for immutability and security.

Q9: Does final guarantee thread safety?
A: No, it only guarantees immutability of references, not synchronization.

Q10: Can a final variable be null?
A: Yes, but once assigned, it cannot be reassigned.