Table of contents
1.
Introduction
2.
What is the Final Keyword in Java?
3.
Characteristics of Final Keyword in Java
4.
Final Variables in Java
4.1.
Example 
5.
Final Methods in Java
5.1.
Example
6.
Final Class in Java
6.1.
Example
7.
When to use Java Final Variable?
8.
Advantages of Final Keyword in Java
9.
Disadvantages of Final Keyword in Java
10.
Frequently asked questions
10.1.
What are the 3 uses of final keyword in Java?
10.2.
What is final class in Java with examples?
10.3.
What is the difference between super and final keyword in Java?
11.
Conclusion
Last Updated: Sep 30, 2024
Easy

Final Keyword in Java

Author Ayush Mishra
0 upvote
Career growth poll
Do you think IIT Guwahati certified course can help you in your career?

Introduction

The final keyword in Java is mainly used to ensure immutability and to prevent inheritance. It can be applied to variables, methods, and classes, making them unchangeable once assigned and prevent any further modifications. Understanding the final keyword is crucial for writing secure, efficient, and predictable Java code, enhancing both performance and reliability. In this article, we’ll be discussing the various uses of this keyword with the help of examples. 

final keyword in java

What is the Final Keyword in Java?

The final keyword in Java is used to apply constraints on variables, methods and classes. The final keyword can be used with classes, methods and variables. Let’s see the explanation.

The Java final keyword is a non-access specifier that is used to limit the scope of a class, variable, or function. If we use the final keyword to initialise a variable, we cannot change its value. When a method is declared final, it cannot be overridden by any subclasses. Furthermore, declaring a class as final prevents other classes from inheriting or extending it.
In other words, additional classes cannot inherit the final classes.

Characteristics of Final Keyword in Java

Here are some characteristics of the Final keyword in Java.

  • Final variables: Final variables are constants that cannot be modified once initialized, ensuring that the value remains constant throughout the program.
     
  • Final methods: Final methods are unchangeable and cannot be modified by subclasses, providing stability to important interface functions.
     
  • Final classes: Final classes cannot be extended, which protects the integrity of the class design and prevents unexpected changes.
     
  • Initialization: Final variables must be initialized during declaration or in the constructor to ensure their values are set and cannot be changed.
     
  • Performance: The use of the Final might lead to performance improvements since the compiler can optimize code more effectively when variables or methods are known to be immutable.
     
  • Security: Security can be improved by using Final, which prevents unauthorized changes to critical data or behavior within the program.

Final Variables in Java

The variables that are declared final in Java become immutable, i.e. their values can’t be changed.

Let’s see, with the help of an example. We’ll make a variable final and try changing its value.

Example 

class Employee {
    final int id = 25; //variable initialised as final
    
    void printvalue(){
        /*
        Trying to change the value of final variable
        gives compilation error
        */
        
        id= 50;
    }
    public static void main(String args[]) {
        Employee e = new Employee();
        e.printvalue();
    }
}
You can also try this code with Online Java Compiler
Run Code

 

Output

Exception in thread "main" java.lang.Error: Unresolved compilation problem: 

The final field Employee.id cannot be assigned

at Employee.printvalue(Employee.java:7)

at Employee.main(Employee.java:12)

Also see, Swap Function in Java

Final Methods in Java

We can declare all or some of the methods of a class as “final”. The methods, once declared final, cannot be overridden by a subclass.

Example

class Employee //class with a final method
{
    final void printvalue() //Method declared as final in Java
    {
        System.out.println("Inside the class employee!!")
    }
}
class Test extends Employee //child class
{
    void printvalue() //trying to override a final method 
    {
        System.out.println("Inside the class Test!!")
    }
    public static void main(String args[]) {
        Test e = new Test();
        e.printvalue();
    }
} 

 

Output


Error: LinkageError occurred while loading main class TestThis

java.lang.VerifyError: class Test overrides final method Employee.printvalue()V

Final Class in Java

We can also declare an entire class as final. Once a class is declared final, it cannot be subclassed, i.e. we cannot extend it.

Example

final class Employee {} //final class in Java
class Test extends Employee //trying to extend a final class
{
    void printvalue() {
        System.out.println("Inside the class Test!!");
    }
    public static void main(String args[]) {
        Test e = new Test();
        e.printvalue();
    }
}

 

Output


Exception in thread "main" java.lang.Error: Unresolved compilation problem: 


at Test.main(TestThis.java:8)

After exploring all about this and final keywords in Java, let’s see some of the frequently asked questions on this topic

When to use Java Final Variable?

When declaring variables as constants in Java, you should use the final keyword to ensure their immutability. When defining immutable values, such as mathematical constants, or when you want to improve thread safety by restricting alterations in a multi-threaded environment, this is extremely helpful. 

Additionally, final variables act as unique identifiers of your design purpose, enhancing code maintainability and lowering the possibility of unintentional changes. Additionally, they might make compiler optimisations possible, which would improve the efficiency of the code.
 

Advantages of Final Keyword in Java

Here are some advantages of Final Keyword in Java.

  • Class Integrity: Final classes cannot be extended or inherited, keeping the class design's integrity. This can help prevent unwanted alterations or additions, ensuring the class performs correctly.
     
  • Method Stability: Subclasses cannot override final methods, giving important techniques in a class's interface stability. This is very useful when you want to verify that a given behavior does not change.
     
  • Performance Improvement: Using the final allows the compiler to optimize the code more effectively since it knows that variables or methods assigned as final cannot be modified. This optimization has the potential to increase performance.

Disadvantages of Final Keyword in Java

Here are some disadvantages of Final Keyword in Java.

  • Reduced Flexibility: Once a variable, method, or class has been tagged as final, it cannot be changed. It reduced flexibility, code change, and customization may be limited.
     
  • Limitations of Inheritance: Final methods and classes cannot be modified or extended, limiting the ability to modify or expand specific features in subclasses. This can at times render code extension difficult.
     
  • Code Maintenance Difficulties: Overuse of the final keyword can make code maintenance more difficult, as changes to final items might require changes in several places in the codebase.

Frequently asked questions

What are the 3 uses of final keyword in Java?

The three main uses of the final keyword are to declare a variable as constant, which enhances the security, declare a method as final so it can't be overridden, and declare a class as final.

What is final class in Java with examples?

A final class in Java is a class that can't be further subclassed. It implies that it can't be extended. For example, if a class is called Animal and declared final, it can't be sub-classed to a class Dog.

What is the difference between super and final keyword in Java?

Java's super keyword enables inheritance and method overrides by allowing access to superclass members from within a subclass or by invoking the superclass constructor directly. The final keyword, on the other hand, is used to establish constants, render methods/classes inheritable, or guarantee variable immutability, hence limiting further modification and inheritance.

Conclusion

In this article, we’ve discussed the various usage of this and final keywords in Java with the help of examples. Java is one of the most popular languages. It finds wide applications in Android development and server development. In-depth knowledge of Java will land you a lucrative job.

After exploring “final keywords in Java,” you can also check out our Guided Path to learn more about a complete, curated preparation guide for coding interviews in tech and product-based companies.

Live masterclass