Get free ebooK with 50 must do coding Question for Product Based Companies solved
Fill the details & get ebook over email
Thank You!
We have sent the Ebook on 50 Must Do Coding Questions for Product Based Companies Solved over your email. All the best!

Final Keyword in Java

Last Updated on June 19, 2023 by Prepbytes

In this article, we will learn about Final Keyword in Java along with various hands-on codes and examples. We will learn to use the final keyword in java with variables, methods, parameters, and also with classes. Then, we will look at the advantages and disadvantages of the final keyword in Java.

Programmers frequently encounter situations in computer programming languages when they must finalize something that cannot be changed or overturned by anyone.

They could occasionally need to finalize variables, forbid methods from being overridden, forbid other classes from the class inheritance, and many other things.

The Final keyword in the Java programming language allows you to put the aforementioned scenario in a box by preventing other entities from overriding or changing the entity that was declared with the final keyword.

What do you mean by Final Keyword in Java

Final keyword in Java is a non-access modifier that shows that an entity cannot be updated more than once. It was added to Java version 7 along with other capabilities.

This implies that if a variable is declared with the final keyword, we cannot alter its value, override a method, or inherit a class.

Let’s use a simple example to explain it. Let’s say you need to create a class that everyone wants to use. How will they proceed? They will undoubtedly inherit your class along with theirs. They will be able to override your efforts in this circumstance.
Therefore, if you do not want anyone to override your logic, you may declare the methods final or just the variable final. If you do not want the variable to be reassigned, you can also define the variable final.

In addition to finishing your methods and variables, all you need to do to prevent anyone from using your work is define a class with the final keywords. Therefore, even if a person tries to inherit, they will encounter a problem.

Final Keyword in Java is used to restrict some of the features of inheritance.

Final Keyword in Java can be Used With?

Final keyword in Java can be used with various entities such as methods, parameters, classes, and variables. This is illustrated below with the help of a diagram:

To understand where we may utilize the last keyword, have a look at the table below:

S.No. Type Description
1 Final Variable Final Variables in Java cannot be re-assigned or given a new value.
2 Final Parameter Final Parameter will ensure that the value of the specified parameter cannot be changed in that function.
3 Final Method Methods declared with the final keyword in Java cannot be overridden by any of its subclasses.
4 Final Class Classes with the final keyword in java cannot be inherited or extended by the other classes.

Variables with Final Keyword in Java

When programmers require a constant variable, they can construct a final variable. A final variable cannot be altered or modified after initialization.

Reassigning values to final variables results in a “Compilation error”. The same may be done with objects, however, in this instance, we can update an object’s property since we have only finalized the object’s reference variable.

Final variables can be used with both primitive and non-primitive data types, such as int, float, double, and char (object references).

How to Initialize Final Variable in Java?

To initialize a Final Variable in Java, we follow the syntax given below:

For primitive Data Types:

final datatype varName = val;

For Non-primitive Data Types:

final  objectName = new ;

The code given below illustrates the usage of final Keyword in Java:

// Final Variable
class Main {
  public static void main (String[] args) {
 
    // initializing a final variable
    final int num = 10;
    
    // Again initializing final variable
    num = 15; // this line will give compilation error
  }
}

Output:

Main.java:9: error: cannot assign a value to final variable num
    num = 15; // this line will give compilation error
    ^

Explanation: In the above code, we have initialized a final variable named “num”. And then we re-assigning another value to “num”. Re-assigning will result in the Compilation Error as shown in the output.

Blank Final Variable in Java

We do not assign the value statically every time while using the final variable. Sometimes we need to define the variable first, then assign a value after a few lines of code have run. We can define the blank-final variable in this scenario.
Note: Ideally, you must assign value to the final variable at the time of defining that variable.

The syntax used for declaring Blank Final Variable in Java:

final datatype varName;
//Statements
varName = value;

The following illustrates the declaration of Blank Variable:

// Blank Final Variable in Java
class BlankFinalVariableExample {
  public static void main (String[] args) {
  	
    // declaring a final variable
    final int num;
    
    // assigning value 
    num = 189; 
    
    System.out.println("Num = " + num);
  }
}

Output:

Num = 189

Explanation: In the above code, we have declared a blank final variable named “num”. Next, we assigned the variable “num” the value of 189 and then we printed the num. This is the way to declare a blank final variable in java

Reference Final Variable in Java

Similar to the Final variable’s behavior, we cannot reassign a variable that refers to any object. Even though we may alter or change the referred-to object’s attribute.

The reference variable cannot be changed, but the attribute of the object to which the variable is linked may. With class objects, arrays, etc., the final reference variable can be utilized.

The following Java Code Explains the above written in the above paragraphs.

class ExampleClass{
    public int value = 5;
}

class Main{
    public static void FinalReference( String args[] ) {

      final ExampleClass example = new ExampleClass(); //declaration
      example.value = 6; // Modifying the object creates no disturbance

      ExampleClass another = new ExampleClass();
      example = another; // Attempting to change the object it refers to, creates an error
     
    }
}

Output:

Main.java:12: error: cannot assign a value to final variable example
      example = another; // Attempting to change the object it refers to, creates an error
      ^

Explanation: In the above code, we have declared an object of class “Example Class” named example. We can change the properties of the object example. But if we try to reassign the object with an object of the same class, it will result in a compile-time error.

A Convention to Remember for Final Variables
All declared final variables are considered constants in Java programmers and are suggested to be written in all capitals in accordance with the Java Code Convention (Uppercase).

Example:

private final int MAX_VALUE = 18978;

Note: A variable declared as final and static are CONSTANTS in Java.

Parameters with Final Keyword in Java

Java also permit us to utilize the final keyword as a parameter for a function. Later on, throughout the function, these parameter values cannot be altered. Therefore, we will encounter the compilation issue even if we attempt to re-initialize it.

Syntax:

  functionName(final  varName) {
    // Statement 1
    // Statement 2
}

Let us understand the working of parameters of Final Keyword in Java with the code given below:

// Final Parameters in Java

class Main {
    public static void fun(final int param){
        param = 5; // This line will give compilation error
        System.out.println(param);
    }
    
    public static void main(String args[]){
    	int num = 56;
    	fun(num);
    }
}

Output:

Main.java:5: error: final parameter param may not be assigned
        param = 5; // This line will give compilation error
        ^

Explanation: In the above code, we have declared a final parameter using final keyword in Java. When we try to change that parameter in the function, it throws a compilation error as given in the output above.

Methods with Final Keyword in Java

Final keyword in java may be used with methods much like final variables. When a method is marked as final, its subclasses cannot override it. Therefore, the system will throw a compile time error if we attempt to override it.

There is no noticeable difference between the final approach and the non-final way if you have considered performance speed.

Syntax:

 class className {
     final  methodName() {
        // code
    }
}

The Final Methods are best explained using the code given below:

class Base{
    //Declaring a final method
    public final void finalMethod(){
        System.out.print("Base Class Method");
    }

}

class Derived extends Base{
    //Overriding the final method throws a compile error
    public final void finalMethod() { 
        System.out.print("Derived"); 
    }
}

Output:

Main.java:11: error: finalMethod() in Derived cannot override finalMethod() in Base
    public final void finalMethod() { 
                      ^
  overridden method is final

Explanation: In the above example, we have declared a method final using final keyword in java name “finalMethod”, when we try to override the method in the derived class. It throws a compilation error because the final methods in Java are forbidden to get overridden.

Classes with Final Keyword in Java

We may use the final keyword in Java classes similarly to how we do with final variables, final parameters, and final methods. These classes are known as the last classes because no other classes may inherit from them.

If we attempt to inherit a class that has been defined as final, the compiler through compilation error.

Classes like Integer, String, and other wrapper classes are also declared as Final Classes.

Note: Even when a class is declared with the final keyword, its objects can still be changed or modified. We just can’t inherit it.

Syntax:

 final class className 
{
    // statements
}

Let us understand using a Java Code:

// Final Class
final class Base {
  public void displayBase() {
    System.out.println("Base Class");
  }
}

//extending final class will givw compilation error
class Derived extends Base{ 
  public void displayDerived() {
    System.out.println("Derived Class");
  }
}

Output:

Main.java:9: error: cannot inherit from final Base
class Derived extends Base{ 
                      ^

Explanation: In the above code, we have declared a final class “Base” and a sub class “Derived” which is extending a final class. Extending a final class will produce compile time error.

Advantages of Final Keyword in Java

The final keyword in Java has several advantages. Some of them are listed below:

  • It improves the performance of a program as the JVM can make certain optimizations with final variables.
  • It provides security by making sure that the value of a final variable cannot be changed once it is initialized.
  • Final Keyword in Java helps to define constants in a program, making it easier to understand the code.
  • It can be used to prevent a class from being subclassed, which can be useful for security and reliability.
  • Final Keyword in Java can be used to prevent a method from being overridden, which can be useful for maintaining the intended behavior of a class or for providing a performance boost.

Disadvantages of Final Keyword in Java

The final keyword in Java has several disadvantages given below in brief:

  • Final Keyword in Java can make the code less flexible, as a final variable cannot be reassigned and a final class cannot be subclassed, a final method cannot be overridden.
  • It can lead to more complex and lengthy code, as methods and classes that use final variables or final classes may need to be rewritten to accommodate them.
  • Final Keyword in Java can make the code less readable and harder to maintain, as the meaning of final variables or final classes may not be immediately clear.
  • It can make testing more difficult, as the behavior of final variables and classes cannot be changed for testing purposes.
  • It can lead to code that is less extensible, as final classes cannot be subclassed and final methods cannot be overridden.

Summary
Final Keyword in Java can be used with the methods, parameters, classes, and with variables.
The final Keyword in Java restricts variables from being re-initialized, methods from being overridden, and classes from inheriting. This Final Keyword helps in restricting the features of Inheritance.

Leave a Reply

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