The final Java keyword is used to denote a constant value in Java which does not allow users to make any changes in the value once defined. You might have used the final Java keyword when you want a variable to always store the same value once declared.
Once you declare the value of entity i,e. Variable, class or method using final, it cannot be assigned again. In this blog, let us throw some light on this very useful keyword from the list of keywords in Java.
Final Keyword in Java
In Java, when we need to declare a variable, class, or method that cannot be overridden or changed once declared we use the final Java keyword. The final Keyword in Java is a non-access modifier that does not allow a variable to be changed or modified.
The final keyword in Java is used to implement immutability and specifies that the given variable must be not modified or extended further. It ensures safety and value prevention.
Final Java Keyword Key Takeaways
- Final Java keywords are non-access modifiers and are immutable.
- The final keyword is used to declare entities like classes, methods, or variables whose value cannot be changed or modified once declared.
- The value stored using the final keyword cannot be reinitialized with another value.
- The final class in Java cannot be extended.
How to use Final Keyword in Java Programs?
The final keyword in Java is used to create constants to prevent a given entity from overriding or inheritance. We declare a variable using the final keyword in Java to represent a value that cannot be changed once it is initialized. There are three instances where we can use the final keyword in Java.
- With variables
- With Methods
- With Classes
Using a final Java keyword with Variables
public class FinalJava_variable{
public static void main(String[] args) { final int MAX_VALUE = 100; System.out.println(“The maximum value is ” + MAX_VALUE); } } |
In the above example, we declared MAX_VALUE with 100 using the final keyword. Now, if we try to assign any other value, for example, 200, it might cause a compile time error.
Using the final keyword with Methods
Methods are user defined functions declared in Java to execute a specified task. Once a method is declared using the final keyword, it cannot be overridden by any other subclasses.
It becomes useful when we do not want any subclass to make any disruption in the behaviour and functionalities of the method.
class Final_Method{
public final void display() { System.out.println(“This is a final method.”); } } class Child extends Final_Method{ // public void display() { // System.out.println(“Cannot override this method.”); // } } |
In the above example, when we try to extend our parent method Final_Method it will throw a compile time error.
Using the final keyword in Java with Classes
A Class in Java declared using the final keyword cannot be overridden by subclass.
final class MathUtilities {
public static double add(double a, double b) { return a + b; } public static double subtract(double a, double b) { return a – b; } } // Attempting to extend this utility class will cause an error: Class ExtendedMathUtilities extends MathUtilities { // Compile-time error: Cannot inherit from final ‘MathUtilities’ // } public class Main { public static void main(String[] args) { double result = MathUtilities.add(10.5, 5.2); System.out.println(“Addition Result: ” + result); } } |
In the above example, attempting to extend the utility class will cause a compile time error as it is not allowed when a class is declared using the final keyword in Java.
Understand Final Keyword in Java
Let us try to understand the final keyword in Java using a simple example given below.
class Car1{
final int speedlimit = 60; void speed(){ speedlimit = 400; } public static void main(String argos[]){ obj.speed(); } } |
Output
In the above example, we tried modifying the value of our variable, “speedlimit” declared with the final keyword. Hence, it throws a compile time error as changing or modifying the value of a entity declared with the final keyword is not allowed.
Final Keyword in Java Example
The final keyword in Java is used at the time of declaring a variable, class or method. Write “final” before the name of the entity to declare it as a final storage. Let us understand the Final Keyword in Java using an example below.
public class FinalVariableExample {
// A final instance variable private final int instanceVariable; // A final static variable (constant) private static final double PI = 3.14159; // Constructor to initialize the final instance variable public FinalVariableExample(int value) { this.instanceVariable = value; // The final instance variable is initialized here } public void demonstrateFinalVariable() { // A final local variable final int localVariable = 5; System.out.println(“Final local variable: ” + localVariable); // Uncommenting the following line would cause a compile-time error: //localVariable = 10; // Error: cannot assign a value to final variable ‘localVariable’ } public void printValues() { System.out.println(“Final instance variable: ” + instanceVariable); System.out.println(“Final static variable (PI): ” + PI); } public static void main(String[] args) { FinalVariableExample example = new FinalVariableExample(20); example.printValues(); example.demonstrateFinalVariable();
// Uncommenting the following line would cause a compile-time error: // PI = 3.14; // Error: cannot assign a value to final variable ‘PI’ } } |
Output
When we try to modify the value of the final variable, it will throw a compile-time error. If we try to change the value of LocalVariable it will throw a compile time error, as shown below.
Effects of using Final Keyword in Java
When we use the final keyword in Java there are certain things we cannot change or modify in a variable, class or method. Let us check some of the major effects of using final keywords in Java.
- You will no longer be able to change the value of an entity, once you declare it with a final keyword.
- It stops method overriding.
- You also cannot apply inheritance to a class or method.
Using the final keyword in Java makes the entity a constant that cannot be changed or altered. It prevents any unwanted modifications in the value of a variable or class.
Learn Java and DSA with PW Skills
Are you looking for a complete interview preparation course to strengthen your programming and data structure knowledge? Enroll in PW Skills Decode Java with DSA program to master data structures and algorithms in Java.
This self-paced course helps you learn important Java frameworks, libraries, and master competitive programming, DSA, web development, and more. Build strong problem-solving skills and logical thinking by solving real-world problems in this course.
Here are some of the Course Highlights:
- Diverse Project Portfolio: Develop a dynamic portfolio with real-world projects.
- Industry Mentorship: Get guidance from experts in the field.
- Interview Opportunities: Access job interviews with leading companies.
- Certification: Earn recognized certificates for course completion.
- Career Growth: Opportunities to advance and fast-track your career.
Ready to elevate your programming skills? Join now for the PW Skills Decode Java with DSA Online Course and start solving real world problems today!
Final Java Keyword FAQs
Q1. What is the Final keyword in Java?
Ans: The final Keyword in Java is a non-access modifier used with an entity (variable, method, or class) whose value cannot be modified once declared. It provides any kind of overriding or changes.
Q2. What are the final rules in Java?
Ans: A final keyword in Java once used with a variable does not allow the following things.
1. A final class cannot be subclassed once declared.
2. Final methods cannot be overridden
3. The final variable cannot be reassigned with another value once initialized.
Q3. Can we declare a constructor as a final entity in Java?
Ans: A constructor cannot be used with a final keyword in Java as a constructor in Java is a special method used to initialize objects. Constructors are not inherited by subclasses and hence, will not have any purpose with the final keyword.