final Keyword in Java
Learn via video course
Overview
Java programming supports the Final keyword which is used in various contexts to describe the entity that can be assigned only once.
Final keyword comes with more functionality and can be used with variables, methods, classes, fields, and function parameters too. We can restrict variables to re-initializing, method to override, and class to inherit using final variables, final methods, and final classes, respectively. Final variable can be used with both primitive and non-primitive data types.
Scope of Article
- This article defines the Final keyword in Java and explains with whom we can use the Final Keyword. We will learn to use this keyword with variables, methods, classes, and function’s parameter.
- The article also illustrates the difference between Final and Immutable classes in Java.
- We will also look at advantages and disadvantages of using the final Keyword in Java, and in which situation we can use the Final keyword.
Introduction
In a computer programming language, programmers often face the situation when they need to finalize something which cannot be modified or overridden by someone.
They might sometimes need to finalize variables, restrict methods to override, prohibit other classes to inherit class, and many other things.
Putting the above situation in a box, Java programming language offers the Final keyword, which restricts other entities to modify or override the entity declared with the final keyword.
What is the Final Keyword in Java?
The keyword Final is a non-access modifier (introduced in Java version 7 with additional functionalities including the final keyword), which illustrates that the entity cannot be modified twice.
That means we cannot change/modify the value of the variable, override method, and inherit class if they are declared with the final keyword.
Let's understand it with an easy example. Assume you have to build a class and everyone else wants to use it. What will they do? Of course, they will inherit your class with theirs. In this situation, they will have access to override your work.
So what you can do is that you can declare the methods final if you do not want others to override your logic, or you can just declare the variable final if you do not want that variable to be re-assigned.
Apart from finalizing methods and variables, if you do not want anyone to even use your work then just declare class with final keywords and you’re done. So, even if someone tries to inherit, they will face an error.
Note:
Inheritance is the best feature when we need to do code reusability. However, sometimes it happens when we are required to set boundaries on extensibility for several reasons. And that's where the Final keyword is used to restrict inheritance.
where we can use the final keyword in java?
Consider the below table to understand where we can use the final keyword.
Type | Description |
---|---|
Final Variable | Variable with final keyword cannot be assigned again |
Final Method | Method with final keyword cannot be overridden by its subclasses |
Final Class | Class with final keywords cannot be extended or inherited from other classes |
The above table is just a brief introduction of the final keyword in Java. Now let's discuss each in detail with code examples.
Final Variable in Java
Programmers can create a final variable when they need to create a constant variable, which means after initializing it cannot be modified or updated.
If we try to modify this variable, the compiler will throw an error. The same way they can do with objects but, in this case we can change the property of objects as we only finalize the reference variable of the object.
Final variables can be used with primitive data types (int, float, double, and char) and non-primitive data types (object references).
Syntax -
Initializing Final Variable in Java
Let's understand it more clearly with a Java program.
Output -
In the above code, as you can see we have declared the integer variable called count as final. After which we were assigning the final variable again with value 15. As a result, we are facing the compilation error by saying that the final variable cannot be re-assigned.
Blank Final Variable
While using the final variable, we are not going to assign the value statically every time. Sometimes we are required to declare the variable first, and then after some lines of execution, we need to assign a value. In this situation, we can declare the blank-final variable.
Admittedly, a good programmer prefers to initialize value at time of declaration while working with the final Keyword in Java, which is not mandatory but recommended.
Syntax -
Let's understand it more clearly with a Java program.
Output -
In the above code, as you can see we have declared the integer variable called count as final. But, instead of initializing it while declaring, we initialize it later and it works completely fine. However, re-assigning it after this step will throw compilation error.
Final Reference Variable
Likewise, the behavior of the Final variable, we cannot re-assign a variable that references to any object. Even Though we can modify/change the object's property it refers to.
It means, we cannot change the reference variable but we can change the property of the object that the variable referred to. Final reference variable can be used with class objects, array, etc.
Syntax -
Example -
Let's understand it more clearly with a Java program.
Output -
In the above code, as you can see we have declared and initialized final reference variable of type StringBuffer with value "Hellow". When we tried to add new string "World" in StringBuffer reference variable, it works fine as we did not change the reference variable but we changed only object's property.
Final Fields
Fields in Java programming language is a variable inside the class, which can also be declared as final. As for the behavior of the final keyword, once we declare a field with the final keyword, it can not be assigned again. Hence, it can be also called a write-once field. A field declared static and final is also called a "constant".
So after declaring the final field, now we cannot change its value. That all means even if the field is in one class, we cannot change its value from another class. Therefore, it makes sense to declare the field static as the value of it will not change anyways.
Example -
Where to initialize -
-
We can initialize static final fields at -
- while declaration
- Inside the static initializer block
-
We can initialize instance final fields -
- while declaration
- Inside the instance initializer block
- Inside the constructor
The final field initialization apart from the above-mentioned places causes compile-time error.
When to use Java Final Variable?
- While creating constant for a program we can use the Final variable (Most of the programmers highly recommended writing the final keyword in uppercase only)
- To restrict the class variable value to update or modify in sub-class.
- To fix some mathematical constant i.e. final double PI = 3.141592653589793;
Convention:
According to the Java Code Convention, all the declared final variables are treated as a constant in Java program, which is advised to be written in all caps (Uppercase).
Final Method in Java
Likewise final variables in Java, we can also use final keywords with methods in Java. When a method is defined as final, then it can not be overridden by its subclasses. So, if we try to override it, the system will throw a compile time error.
If you have thought in your mind regarding performance speed then there is no relevant difference between the final method and the non-final method.
Syntax -
Let's understand it more clearly with a Java program.
Output -
In the above code, we have declared two classes Scaler and InterviewBit. Class InterviewBit inherited class Scaler, and so it also tried to override the final method of class Scaler. As the final method cannot be overridden, the program throws the compilation time error by saying - display() in InterveiwBit cannot override display() in Scaler.
Purpose of Java Final Methods
As we now understand the concept of final methods in java and how we can implement it, now let's understand in which situation we need to use the final methods.
The final method is used to restrict unexpected behavior of child classes by adding or modifying methods that may lead to interrupting the consistency of the class.
In such a case, it is preferred to declare some or all methods in class as Final as per requirements.
If we take an example from Java itself then the Thread class is the best example to understand the above reason. We can extend the Thread class and can also create a new custom one. However, we can not override its method isAlive() (checks if a thread is alive or not) as it was defined as the final method.
Let's understand it from a Java program.
Output -
As you can see, there are two methods in class Calculation - premiumCalculation and fixedCalculation. Here, we defined fixedCalculation as a final method so no other can override the logic of this class. On the other hand, premiumCalculation can be overriden.
Final Class in Java
Likewise with the final variables and final methods, we can also use the final keyword with Java classes. These classes are called the final classes, which can not be inherited by any other classes.
So, if we try to inherit a class which is declared as a final, the system will throw a compile time error.
Classes like Integer, String, and many other wrapper classes are an example of Final classes.
Syntax -
Example -
Let's understand it more clearly with a Java program.
Output -
Note:
Declaring class with final keyword doesn't mean we can not change/modify the object of that class. We just can not inherit it.
Java final parameter
As we already worked with functions, we know how to pass values to functions and return result after performing some operation. The value that we passed to function is called a Parameter.
Interestingly, Java also allows us to use the final keyword for a function's parameter. These parameter value can not be changed later in function. So, even if we try to re-initialize it, we will face the compilation error.
Syntax -
Let's understand it more clearly with a Java program.
Output -
The above code created a class X’s object and accessed its method. But, here we have used the final keyword in the function's parameter (final int value). So, when we try to change the variable value, the system throws the error saying that the final parameter value may not be assigned.
Final and Immutable Class in Java
First let's discuss both term -
- Final - Final means that we can not change or modify the reference variable of an object, to point or reference to another object.
Example -Here, we cannot re-initialize the reference varibale declared as final.
- Immutable - Immutable means that we can not change an object's actual value, but we can change its reference variable to point to another object. I.e. String Class.
Example -As you can see, we can change the reference variable to point another object, but we cannot do anything to change the object's value "Hey".
In Java, Final is used to write immutable classes. Without making a class Final, we cannot make it immutable, and therefore, the keyword final is needed (necessary but not sufficient) to implement an immutable class. In Java, all the wrapper classes (like Integer, Boolean, Byte, Short) and String class is immutable.
Advantages and Disadvantages of Final variable in java
Advantages
- Final variable improves performance during runtime. In JVM the compiled code can improve the performance at a runtime, and for the JVM final variables are compiled code.
- Final variable can be stored in cache, not just by JVM but also by the application.
- final Keyword in Java is needed to implement an immutable class.
Disadvantages
- Final variable works seamlessly only with primitive or immutable type variables. Moreover, it doesn't give you a guarantee that you can not modify the state/value of a variable (Non-primitive). It just does not allow us to reassign the reference to any other objects after initialization.
For instance -
That means in many cases, final variable still doesn't make it easier for coders to know what exactly is happening inside the code. Which may lead to misunderstanding and bugs in the application.
Note:
All the declared variables in the Java interface are inherently final.
FAQs
1. Is the final method inherited?
Yes, we can inherit the final method. However, we can not override it.
2. What is the blank or uninitialized final variable?
The final variable which is not initialized while declaring is called blank or uninitialized final variable.
3. What is the final parameter?
The argument or parameter of any function declared as final, then it is called final parameter. The value of the final parameter can not be modified later in that function.
4. Can we declare a constructor final?
No. Because the constructor can never be inherited. In the concept of inheritance, we can only inherit members of the parent or super class but not a constructor. Therefore, we can never add or modify the super class’s constructor. Hence, no need to declare the constructor as final.
Conclusion
- The final Keyword in Javacan be used with local variables, member variables, methods, and classes.
- The final Keyword in Java can be used with primitive data types and non-primitive data types variables.
- We cannot change/modify the value of a variable, override a method, and inherit a class if they are declared with the final Keyword in Java.
- Final methods help to ensure that they functionality cannot be changed by any class which inherits the parent class.
- A final variable which is left without initialization is known as blank final variable.
- While creating a final member variable, it must be assigned while declaring or inside the constructor, else it will throw compilation errors.
- A final reference variable cannot be changed, however the properties of the object, that the variable refers to, can be changed.
- A final class cannot be inherited. However, we can still modify the properties of its objects.
- The value of an argument, which is declared as final, cannot be changed within the method body.