What is final keyword in Java

In java final is a keyword which is quite used in java programs. In real life when we say something is final, it means we can not change that later, the same applies with final keyword in java as well. When a member in java is declared as final, it's value or definition can not be changed later. Let's see different uses and examples of final keyword in java.

What is the use of final keyword in Java

The final keyword is used to make a member as final. Once a member is declared as final, it's definition or value can not be changed later. In java final keyword can be used with following members :

  • Variable - Value of final variable can not be changed once initialized.
  • Method - Final method can not be overridden.
  • Class - Final classes can not be inherited.

What is final variable in Java

A variable declared with final keyword is known as final variable. Once a final variable is initialized with some value, we can not change it's values later in the program, that is what the final keyword do when used with variable.

The syntax of declaring final variable is :

 final data_type var_name = value;
 Ex.
 final int total_hours = 24; 
 final double PI = 3.141592653589793; 
 // Value can be assigned in constructor as well

Note : final keyword must be used before the data type of variable.

Java program using final keyword

 class FinalVariableProgram {  
   static final double PI = 3.141592653589793; 
     
   public static void main(String [] args) {
     // Doing below will result in compilation error
     // PI = 3.14; 
     FinalVariableProgram fvp = new FinalVariableProgram();
     System.out.println("Value of PI = "+fvp.PI);  ; 
     final int total_hours = 24; 
     // Doing below will result in compilation error
     // total_hours = 20; 
     System.out.println("Total hour in a day = "+total_hours);     
   }
 }

Output:

Value of PI = 3.141592653589793
Total hour in a day = 24

The final keyword can be used with all variable types, local, instance and static variables. It does the same thing with all variable types. Once you assigned some value to a final variable, you can not re-assign some other value later.

Reference(Non primitive type) variable in java can also be declared as final. Once such variables are assigned some reference, they can not refer to any other object later in the program. Remember the object that is assigned to a final reference variable can change it's own properties or behavior. It's own properties and behavior won't be final.

A final variable which is created inside method, constructor or block is known as local final variable. These variables must be initialized only once, after that you can not change it's value later in the program.

What is the difference between normal variable and final variable in Java ?

The only difference is that incase of normal variable we can re-assign new value any number of times while incase of final variable we can not re-assign after once. Value of final variable is assigned only once.

Initializing final variable in Java

  • The most common way is to initialize the value of final variable while declaring it. If it is not initialized we call it blank final variable, which must be initialized using either of below approaches.
  • An instance final variable can be assigned value in instance initializer block or in constructor. If the class contains more than one constructor, then it must be initialized in all of the constructor otherwise compiler will throw error.
  • A static final variable can be initialized inside static block.

Program below demonstrates different ways of initializing final variable in java.

 class FinalVariableInitialization {  
   final int maxValue = 100; 
   final int minValue; 
   final int totalValue; 
   static final double PI; 
   
   // Initializing static final variable in static block 
   static {
      PI = 3.141592653589793;
    }
    // Initializing instance final variable in instance block
    {
      totalValue = 150;
    }
    // Initializing instance final variable in constructor
    public FinalVariableInitialization() {
      minValue = 50;
    }    
   public static void main(String [] args) {
     FinalVariableInitialization ob = new FinalVariableInitialization();
     System.out.println("maxValue = "+ob.maxValue+",  minValue = "+ob.minValue);
     System.out.println("totalValue = "+ob.totalValue+",  PI = "+PI);     
   }
 }

Output:

maxValue = 100,  minValue = 50
totalValue = 150,  PI = 3.141592653589793

What is final method in Java

A method declared with final keyword is known as final method. Once a method is declared as final, it can not be overridden in subclasses, hence you won't be able to change the definition of that method in subclasses, that is what the purpose of final keyword is, it doesn't allow subclasses to change/modify the definition of that method.

As we know that in java a subclass inherits the method of parent class and modifies the definition of that method if needed. In order to stop this we can use final keyword with method declaration which stops the subclasses to override that method.

The syntax of declaring final method is :

 final return_type methodName() { ... } 
 Ex.
 final void print() { ... }

Note : final keyword must be used before the return type of method.

Program in java using final method

 class A {      
   final void print() {
      System.out.println("Printing from class A");
    }
  }
 class B extends A {     
   // Below code will result in compilation error
   void print() { 
      System.out.println("Printing from class B");
    }
   public static void main(String [] args) {
      System.out.println("Trying to override final method of class A");
    }
  }

Above program won't compile as subclass B is trying to override the final method of parent class A. If you remove the print method from class B, the program will compile and execute successfully. The compilation error will look something like below :

Output:

B.java:8: error: print() in B cannot override print() in A
   void print() {
        ^
  overridden method is final
1 error

Can we use final keyword with static methods as well ?

Yes we can use. The subclasses won't be able to hide such methods of parent class. We can use final keyword with main method as well.

Can we overload final method in java ?

Yes, final method in java can be overloaded.

Can we call final method of a class in subclasses ?

Yes we can, that will not give any issue.

What is final class in Java

A class declared with final keyword is known as final class. Once a class is declared as final, it can not be inherited, hence you won't be able to override/hide any of it's variable or method. That is what the purpose of final keyword is, it makes the class definition as final.

In other words if you don't want to allow your class to be inherited by other classes, declare your class using final keyword.

The syntax of declaring final class is :

 final class className { ... }
 Ex.
 final class MyClass { ... } 

Note : final keyword must be used before class keyword.

final class program in java

 final class A {      
    void print() {
      System.out.println("Hello form class A");
    }
  }  
 class B extends A {     
    public static void main(String [] args) {
      System.out.println("Hello form class B");       
    }
  }

Above program won't compile as the class B is trying to inherit the class A which is declared as final. Classes declared with final keyword can not be inherited at all.

What is the use of final class in Java

  • It stops other classes to inherit the class, So whatever you have defined, that will be final.
  • To create an immutable class in java you should declare your class as final. Many predefined java classes like String, StringBuffer, StringBuilder etc are final classes.
  • It enhances the security of your class, as it cannot be extended/modified by other classes.

When to use final keyword in Java

For variables, if you know that the value of the variable don't need be changed throughout the program, declare that variable as final variable. In other words for constant values you should use final variable, for example PI.

Similarly for methods, if you don't want your methods to be overridden/modified by subclasses, declare them as final methods. For classes, if you don't want your class to be inherited/modified by any other classes, declare them as final classes.

★★★
  • Constructors or blocks can not be declared as final.
  • final is not an access modifier
  • We can create the object of final class but can not extend it.
  • We can also declare the parameter of a method as final.
  • We can not initialize instance final variable inside method.
  • Generally constants are declared as final variable, the good practice is to name these variables in uppercase letter.