Final Keyword In Java

The final keyword in Java is used to restrict the user. It is also known as a non-access modifier. We can use the final keyword with:

  • Variable
  • Method
  • Class
  • Parameter
  • 1. Java final variable

A variable that is marked as final is referred to as a final variable. Once a final variable is assigned a value, it cannot be altered throughout the program execution, resembling the behavior of a constant.

Syntax

Here is the syntax to declare a final variable:

Example

final datatype VARIABLE_NAME=VALUE;

Example of final Variable

Within the code snippet provided, the Main class contains a constant variable referred to as SPEEDLIMIT, which is declared as final. Attempting to modify the value of the constant SPEEDLIMIT to 400 through the execution of the run method does not result in a change. This is due to the nature of final variables, as they are unable to be altered once they have been initialized.

The subsequent demonstration illustrates that a final variable is immutable after it has been assigned a value.

Example

class Main {  

  final int SPEED_LIMIT=90;    //final variable  

  void run() {  

   SPEED_LIMIT=400;   //we cannot change the final variable  

  }  

  public static void main(String args[]) {  

  Main obj=new  Main();  

  obj.run();  

  }  

 }

Upon compiling the aforementioned code snippet, an error is displayed during compile time, shown below:

Example

error: cannot assign a value to final variable SPEED_LIMIT

2. Java final Method

When a method is declared as final, it is referred to as a final method. Subclasses are prohibited from overriding a final method.

Syntax:

Here is the syntax to declare a final method:

Example

final void paint() {

}

Example of final Method

The subsequent illustration showcases the inability to override a final method in a subclass.

Example

class Bike {  

  final void run() {   //final method

   System.out.println("running"); }  

}  

public class Main extends Bike {  

   //We cannot override the final method  

   void run(){System.out.println("running safely with 100kmph");

}  

    public static void main(String args[]) {  

   Main obj= new Main();  

   obj.run();  

   }  

}

Compiling the code provided above results in a compile-time error, which is displayed as:

Example

Main.java:7: error: run() in Main cannot override run() in Bike

   void run(){System.out.println("running safely with 100kmph");

        ^

  overridden method is final

1 error

3. Java final Class

When a class is defined using the final keyword, it is referred to as a final class. It's important to understand that a final class cannot be extended or inherited.

Syntax:

Here is the syntax to declare a final class:

Example

final class Square {

//statement 

}

Example of final Class

The upcoming example illustrates that a class declared as final cannot serve as a base class for inheritance.

Example

final class Bike {}  

//We cannot inherit the final class  

public class Main extends Bike 

{  

   void run()

   {

       System.out.println("running safely with 100kmph");   

   }  

     public static void main(String args[]) 

     {  

       Main obj = new Main();  

       obj.run();  

   }  

}

Upon compiling the code provided above, a compile-time error is displayed as shown below:

Example

Main.java:3: error: cannot inherit from final Bike

public class Main extends Bike 

                          ^

1 error

Inheriting a Final Method

A child class has the ability to inherit a final method from its parent class, but it is restricted from being overridden. This feature is beneficial when you aim to maintain the method's implementation without alterations in subclasses.

Example

The subsequent illustration showcases the inheritance of a method that has been declared final:

Example

class Bike {    

    final void run() { 

        System.out.println("running...");   

    }    

}    



public class Main extends Bike {    

    public static void main(String args[]) {    

        new Main().run();    

    }    

}

Output:

Output

running...

Blank or Uninitialized Final Variable

A blank final variable is a final variable that lacks initialization during declaration and, once initialized, cannot be altered. Such variables are valuable when a value needs to be assigned during object instantiation, like an employee's PAN card number.

Example

Below is a code snippet that demonstrates the utilization of a final variable that is either left blank or uninitialized:

Example

class Student {    

    int id;    

    String name;    

    final String PAN_CARD_NUMBER;    

    ...

}

Initialization of a Blank Final Variable

An uninitialized final variable can only be assigned a value within a constructor, making it a blank final variable.

Example

Below is an illustration showcasing the process of initializing a blank final variable:

Example

public class Main {    

    final int speedlimit;   // blank final variable    



    Main() {    

        speedlimit = 70;    

        System.out.println(speedlimit);    

    }    



    public static void main(String args[]) {    

        new Main();    

    }    

}

Output:

Static Blank Final Variable

A static final variable that remains uninitialized at declaration is referred to as a static blank final variable. Initialization of this variable is only possible within a static block.

Example

The illustration below showcases the implementation of a static final variable that is left uninitialized:

Example

public class Main {    

    static final int data;   // static blank final variable    



    static {    

        data = 50;    

    }    



    public static void main(String args[]) {    

        System.out.println(Main.data);    

    }    

}

Output:

Final Parameter

A final parameter is a parameter in a method that retains its value and cannot be altered within the method.

Example

Below is an example showcasing the utilization of a final parameter:

Example

public class Main {  

    public void value(final int num) {  

        System.out.println(num);  

    }  



    public static void main(String args[]) {  

        Main obj = new Main();  

        obj.value(500);  

    }  

}

Output:

Advantages of the final Keyword

Here are the key advantages of using the final Keyword in Java, which enhance the security, performance, and maintainability of our code:

  • Improved Performance: The final keyword enables the compiler to optimise code execution because final variables have fixed values, which results in enhanced efficiency.
  • Security: Declaring classes and methods as final prevents unintended modifications, ensuring core functionality remains intact.
  • Clear Design Intent: It signals to developers that a class or method should remain unchanged, improving code readability and maintainability.
  • Immutability: Helps create immutable objects, which are essential for functional programming and multi-threaded applications.
  • Thread Safety: Final fields ensure consistency in concurrent environments, preventing unexpected modifications by different threads.
  • Final Constructor Limitation

It is not possible to mark a constructor as final because constructors are not inherited, and the final keyword is primarily utilized to prevent inheritance and overriding.

Characteristics of the final Keyword

There are several characteristics of the final keyword in Java. Some of them are as follows:

  • Immutability: When applied to variables, classes, or methods, the final keyword ensures that values remain unchanged once assigned, preventing modifications.
  • Method Overriding Restrictions: A final method cannot be overridden in subclasses, helping maintain security and ensuring consistent behavior.
  • Thread Safety: The final keyword enhances clarity in multi-threaded applications by ensuring that values remain constant, reducing unintended modifications.

Input Required

This code uses input(). Please provide values below: