The Wayback Machine - https://web.archive.org/web/20240920211407/https://www.geeksforgeeks.org/final-keyword-in-java/
Open In App

final Keyword in Java

Last Updated : 31 Jul, 2024
Summarize
Comments
Improve
Suggest changes
Like Article
Like
Save
Share
Report
News Follow

The final method in Java is used as a non-access modifier applicable only to a variable, a method, or a class. It is used to restrict a user in Java.

The following are different contexts where the final is used:

  1. Variable
  2. Method
  3. Class

FinalkeywordinJava-copy

Characteristics of final keyword in Java:

In Java, the final keyword is used to indicate that a variable, method, or class cannot be modified or extended. Here are some of its characteristics:

  • Final variables: When a variable is declared as final, its value cannot be changed once it has been initialized. This is useful for declaring constants or other values that should not be modified.
  • Final methods: When a method is declared as final, it cannot be overridden by a subclass. This is useful for methods that are part of a class’s public API and should not be modified by subclasses.
  • Final classes: When a class is declared as final, it cannot be extended by a subclass. This is useful for classes that are intended to be used as is and should not be modified or extended.
  • Initialization: Final variables must be initialized either at the time of declaration or in the constructor of the class. This ensures that the value of the variable is set and cannot be changed.
  • Performance: The use of a final can sometimes improve performance, as the compiler can optimize the code more effectively when it knows that a variable or method cannot be changed.
  • Security: The final can help improve security by preventing malicious code from modifying sensitive data or behavior.

Overall, the final keyword is a useful tool for improving code quality and ensuring that certain aspects of a program cannot be modified or extended. By declaring variables, methods, and classes as final, developers can write more secure, robust, and maintainable code. 

Java Final Variable

When a variable is declared with the final keyword, its value can’t be changed, essentially, a constant. This also means that you must initialize a final variable.

If the final variable is a reference, this means that the variable cannot be re-bound to reference another object, but the internal state of the object pointed by that reference variable can be changed i.e. you can add or remove elements from the final array or final collection.

It is good practice to represent final variables in all uppercase, using underscore to separate words.

Example:

Java
public class ConstantExample {
    public static void main(String[] args) {
        // Define a constant variable PI
        final double PI = 3.14159;

        // Print the value of PI
        System.out.println("Value of PI: " + PI);
    }
}

Output
Value of PI: 3.14159

Output:

Value of PI: 3.14159

Different Methods of Using Final Variable

Let’s see different methods that we can use final variable in Java.

1. final Variable

Example:

// Final variable
final int THRESHOLD = 5;

2. Blank final Variable

Example:

// Blank final variable
final int THRESHOLD;

3. Static final Variable

Example:

// Final static variable PI
static final double PI = 3.141592653589793;

4. Static Blank final Variable

Example:

// Blank final static  variable
static final double PI;

Initializing a final Variable 

We must initialize a final variable, otherwise, the compiler will throw a compile-time error. A final variable can only be initialized once, either via an initializer or an assignment statement. There are three ways to initialize a final variable: 

  1. You can initialize a final variable when it is declared. This approach is the most common. A final variable is called a blank final variable if it is not initialized while declaration. Below are the two ways to initialize a blank final variable.
  2. A blank final variable can be initialized inside an instance-initializer block or the constructor. If you have more than one constructor in your class then it must be initialized in all of them, otherwise, a compile-time error will be thrown.
  3. A blank final static variable can be initialized inside a static block.

Let us see these two different ways of initializing a final variable

Example:

Java
// Java Program to demonstrate Different
// Ways of Initializing a final Variable

// Main class 
class GFG {
  
    // a final variable
    // direct initialize
    final int THRESHOLD = 5;
    
    // a blank final variable
    final int CAPACITY;
    
    // another blank final variable
    final int  MINIMUM;
    
    // a final static variable PI
    // direct initialize
    static final double PI = 3.141592653589793;
    
    // a  blank final static  variable
    static final double EULERCONSTANT;
    
    // instance initializer block for 
    // initializing CAPACITY
    {
        CAPACITY = 25;
    }
    
    // static initializer block for 
    // initializing EULERCONSTANT
    static{
        EULERCONSTANT = 2.3;
    }
    
    // constructor for initializing MINIMUM
    // Note that if there are more than one
    // constructor, you must initialize MINIMUM
    // in them also
    public GFG() 
    {
        MINIMUM = -1;
    }
        
}

 
There was no main method in the above code as it was simply for illustration purposes to get a better understanding to draw conclusions:

Observation 1: When to use a final variable?

The only difference between a normal variable and a final variable is that we can re-assign the value to a normal variable but we cannot change the value of a final variable once assigned. Hence final variables must be used only for the values that we want to remain constant throughout the execution of the program.

Observation 2: Reference final variable. 

When a final variable is a reference to an object, then this final variable is called the reference final variable. For example, a final StringBuffer variable looks defined below as follows:

final StringBuffer sb;

As we all know a final variable cannot be re-assign. But in the case of a reference final variable, the internal state of the object pointed by that reference variable can be changed. Note that this is not re-assigning. 

This property of the final is called non-transitivity. To understand what is meant by the internal state of the object as shown in the below example as follows:

Example 1:

Java
// Java Program to demonstrate
// Reference of Final Variable

// Main class
class GFG {

    // Main driver method
    public static void main(String[] args)
    {
        // Creating an object of StringBuilder class
        // Final reference variable
        final StringBuilder sb = new StringBuilder("Geeks");

        // Printing the element in StringBuilder object
        System.out.println(sb);

        // changing internal state of object reference by
        //  final reference variable sb
        sb.append("ForGeeks");

        // Again printing the element in StringBuilder
        // object after appending above element in it
        System.out.println(sb);
    }
}

Output
Geeks
GeeksForGeeks

The non-transitivity property also applies to arrays, because arrays are objects in Java. Arrays with the final keyword are also called final arrays.

Note: As discussed above, a final variable cannot be reassign, doing it will throw compile-time error.

Example 2:

Java
// Java Program to Demonstrate Re-assigning
// Final Variable will throw Compile-time Error

// Main class
class GFG {

    // Declaring and customly initializing
    // static final variable
    static final int CAPACITY = 4;

    // Main driver method
    public static void main(String args[])
    {

        // Re-assigning final variable
        // will throw compile-time error
        CAPACITY = 5;
    }
}

Output: 

Final Variable Throwing Compile-time Error

Remember: When a final variable is created inside a method/constructor/block, it is called local final variable, and it must initialize once where it is created. See below program for local final variable.

Example:

Java
// Java program to demonstrate
// local final variable

// Main class
class GFG {

    // Main driver method
    public static void main(String args[])
    {
        // Declaring local final variable
        final int i;

        // Now initializing it with integer value
        i = 20;

        // Printing the value on console
        System.out.println(i);
    }
}

Output
20

Remember these key points as perceived before moving forward as listed below as follows:

  1. Note the difference between C++ const variables and Java final variables. const variables in C++ must be assigned a value when declared. For final variables in Java, it is not necessary as we see in the above examples. A final variable can be assigned value later, but only once.
  2. final with foreach loop: final with for-each statement is a legal statement.

Example:

Java
// Java Program to demonstrate Final
// with for-each Statement

// Main class
class GFG {

    // Main driver method
    public static void main(String[] args)
    {

        // Declaring and initializing
        // custom integer array
        int arr[] = { 1, 2, 3 };

        // final with for-each statement
        // legal statement
        for (final int i : arr)
            System.out.print(i + " ");
    }
}

Output
1 2 3 

Output explanation: Since the “i” variable goes out of scope with each iteration of the loop, it is re-declared each iteration, allowing the same token (i) to be used to represent multiple variables. 

Example:

Java
public class Example {
    public static void main(String[] args) {
        final int VALUE = 10; // declaring a final variable
        
        System.out.println("The value is: " + VALUE);
        // VALUE = 20; // uncommenting this line will cause a compiler error
        // System.out.println("The new value is: " + VALUE);
        
        final String MESSAGE = "Hello, world!"; // declaring a final variable
        System.out.println(MESSAGE);
        
        MyClass myObj = new MyClass();
        myObj.printMessage();
        myObj.printFinalMessage();
        
        // MyOtherClass extends MyClass {} // uncommenting this line will cause a compiler error
    }
}

class MyClass {
    final String message = "Hello!"; // declaring a final instance variable
    
    void printMessage() {
        System.out.println(message);
    }
    
    void printFinalMessage() {
        final String finalMessage = "Hello, final!";
        System.out.println(finalMessage);
    }
}

final class MyOtherClass { // declaring a final class
    // ...
}

Output
The value is: 10
Hello, world!
Hello!
Hello, final!

Java Final classes

When a class is declared with the final keyword in Java, it is called a final class. A final class cannot be extended(inherited). 

There are two uses of a final class: 

Usage 1: One is definitely to prevent inheritance, as final classes cannot be extended. For example, all Wrapper Classes like Integer, Float, etc. are final classes. We can not extend them.

final class A
{
// methods and fields
}
// The following class is illegal
class B extends A
{
// COMPILE-ERROR! Can't subclass A
}

Usage 2: The other use of final with classes is to create an immutable class like the predefined String class. One can not make a class immutable without making it final.

Java Final Method

When a method is declared with final keyword, it is called a final method in Java. A final method cannot be overridden. 

The Object class does this—a number of its methods are final. We must declare methods with the final keyword for which we are required to follow the same implementation throughout all the derived classes. 

Illustration: Final keyword with a method 

class A 
{
final void m1()
{
System.out.println("This is a final method.");
}
}
class B extends A
{
void m1()
{
// Compile-error! We can not override
System.out.println("Illegal!");
}
}

Advantages of final Keyword in Java:

The final keyword in Java provides several advantages, including:

  • Ensuring immutability: When a variable or reference is marked as final, its value cannot be changed once it is assigned. This helps ensure that data is immutable and cannot be accidentally or maliciously modified.
  • Improving performance: The use of the final can sometimes help improve performance, as the Java Virtual Machine (JVM) can optimize code more effectively when it knows that certain values or references cannot be changed.
  • Making code easier to understand: By declaring variables, methods, or classes as final, developers can make their code easier to understand and reason about. When a value or reference is marked as final, it is clear that it will not change, which can simplify code analysis and debugging.
  • Promoting code reuse: By declaring methods as final, developers can prevent subclasses from overriding them. This can help promote code reuse and reduce duplication, as subclasses must use the parent class’s implementation of the method.
  • Enhancing security: The use of final can help enhance security by preventing malicious code from modifying sensitive data or behavior.

Overall, the final keyword is a useful tool for improving code quality and ensuring that certain aspects of a program cannot be modified. By declaring variables, methods, and classes as final, developers can write more secure, robust, and maintainable code.

For more examples and behavior of final methods and final classes, please see Using final with inheritance. Please see the abstract in java article for differences between the final and the abstract.

Related Interview Question(Important): Difference between final, finally, and finalize in Java

Conclusion

The final Keyword in Java is a method to make user-restricted variables, methods, or classes. In this tutorial, we cover Java’s final keyword in detail and understand all its contexts.

The contexts are explained with Java programs in examples, providing a complete understanding of the subject.

Java Final Keyword – FAQs

What is a final method in Java?

Yes, A final method is inherited by child class, but it cannot be overridden or modified in the subclass.

Is final method inherited?

No, in Java a final method can not be inherited by a subclass. This means that a subclass can not override a final method.

What is the final keyword and static keyword in Java?

Final Keyword: It is used to declare variables, methods, or classes as unmodifiable.

Static keyword: It is used to declare class members (variables and methods) that belong to the class itself, not individual objects.

Can we write final keyword with a string in Java?

Yes, you can declare a variable with final keyword and assign string literal to it.



Previous Article
Next Article

Similar Reads

final vs Immutability in Java
final: In Java, final is a modifier that is used for class, method, and variable also. When a variable is declared with the final keyword, its value can’t be modified, essentially, a constant. Immutability: In simple terms, immutability means unchanging overtime or being unable to be changed. In Java, we know that String objects are immutable means
3 min read
Difference between Final and Abstract in Java
In this article, the difference between the abstract class and the final class is discussed. Before getting into the differences, lets first understand what each of this means. Final Class: A class which is declared with the "Final" keyword is known as the final class. The final keyword is used to finalize the implementations of the classes, the me
4 min read
Why a Constructor can not be final, static or abstract in Java?
Prerequisite: Inheritance in Java Constructor in java is a special type of method which is different from normal java methods/ordinary methods. Constructors are used to initialize an object. Automatically a constructor is called when an object of a class is created. It is syntactically similar to a method but it has the same name as its class and a
6 min read
Can We Override Final Method in Java?
A method in a subclass is said to Override a method in its superclass if that method has a signature identical to a method in its superclass. When this method is called by an object of the subclass, then always the Overridden version will be called. In other words, the method which was Overridden in the superclass will become hidden. The JVM has 2
3 min read
Private vs Final Access Modifier in Java
Whenever we are writing our classes we have to provide some information about our classes to the JVM like whether this class can be accessed from anywhere or not, whether child class creation is possible or not, whether object creation is possible or not etc. we can specify this information by using an appropriate keyword in java called access modi
3 min read
Private vs Protected vs Final Access Modifier in Java
Whenever we are writing our classes, we have to provide some information about our classes to the JVM like whether this class can be accessed from anywhere or not, whether child class creation is possible or not, whether object creation is possible or not, etc. we can specify this information by using an appropriate keyword in java called access mo
5 min read
Can We Extend final Method in Java?
Final method in java can be extended but alongside the main concept to be taken into consideration is that extend means that you can extend that particular class or not which is having final method, but you can not override that final method. One more case where you can not extend that final method is the class that contains the final method is als
3 min read
Effectively Final Variable in Java with Examples
A final variable is a variable that is declared with a keyword known as 'final'. Example: final int number; number = 77; The Effectively Final variable is a local variable that follows the following properties are listed below as follows: Not defined as finalAssigned to ONLY once. Any local variable or parameter that's assigned a worth just one occ
4 min read
Protected vs Final Access Modifier in Java
Whenever we are writing our classes, we have to provide some information about our classes to the JVM like whether this class can be accessed from anywhere or not, whether child class creation is possible or not, whether object creation is possible or not, etc. we can specify this information by using an appropriate keyword in java called access mo
5 min read
Java - Final vs Static Access Modifier
Final keyword is used in different contexts. First of all, final is a non-access modifier applicable only to a variable, a method, or a class. Following are different contexts where final is used. While the static keyword in Java is mainly used for memory management. The static keyword in Java is used to share the same variable or method of a given
5 min read
Assigning values to static final variables in Java
Assigning values to static final variables in Java: In Java, non-static final variables can be assigned a value either in constructor or with the declaration. But, static final variables cannot be assigned value in constructor; they must be assigned a value with their declaration.For example, following program works fine. Java Code class Test { //
1 min read
Private and final methods in Java
When we use final specifier with a method, the method cannot be overridden in any of the inheriting classes. Methods are made final due to design reasons. Since private methods are inaccessible, they are implicitly final in Java. So adding final specifier to a private method doesn't add any value. It may in-fact cause unnecessary confusion. class B
1 min read
final, finally and finalize in Java
This is an important question concerning the interview point of view. final keyword final (lowercase) is a reserved keyword in java. We can't use it as an identifier, as it is reserved. We can use this keyword with variables, methods, and also with classes. The final keyword in java has a different meaning depending upon whether it is applied to a
13 min read
Blank Final in Java
A final variable in Java can be assigned a value only once, we can assign a value either in declaration or later. final int i = 10; i = 30; // Error because i is final. A blank final variable in Java is a final variable that is not initialized during declaration. Below is a simple example of blank final. // A simple blank final example final int i;
2 min read
Using final with Inheritance in Java
Prerequisite - Overriding in java, Inheritance final is a keyword in java used for restricting some functionalities. We can declare variables, methods, and classes with the final keyword. Using final with inheritance During inheritance, we must declare methods with the final keyword for which we are required to follow the same implementation throug
4 min read
Output of Java programs | Set 24 (Final Modifier)
Difficulty level : Easy Prerequisite : final keyword in java Predict the output of following Java Programs: What will be output of following program? class Test { final int MAXIMUM; final double PI; public Test(int max) { MAXIMUM = max; } public Test(double pi) { PI = pi; } public static void main(String[] args) { Test t1 = new Test(1500); Test t2
3 min read
Instance variable as final in Java
Instance variable: As we all know that when the value of variable is varied from object to object then that type of variable is known as instance variable. The instance variable is declared inside a class but not within any method, constructor, block etc. If we don’t initialize an instance variable, then JVM automatically provide default value acco
3 min read
Final static variable in Java
Prerequisite : static variables, final keyword Static variable: When the value of a variable is not varied, then it is a not good choice to go for instance variable. At that time we can add static modifier to that variable. Whenever we declare variable as static, then at the class level a single variable is created which is shared with the objects.
3 min read
Final local variables in Java
Prerequisite : final keyword, Variables, Scope of Variables A local variable in Java is a variable that’s declared within the body of a method. Then you can use the variable only within that method. Other methods in the class aren’t even aware that the variable exists. If we are declaring a local variable then we should initialize it within the blo
2 min read
Static and non static blank final variables in Java
A variable provides us with named storage that our programs can manipulate. There are two types of data variables in a class: Instance variables : Instance variables are declared in a class, but outside a method, constructor or any block. When a space is allocated for an object in the heap, a slot for each instance variable value is created. Instan
5 min read
final variables in Java
In Java, we can use final keyword with variables, methods, and classes. When the final keyword is used with a variable of primitive data types such as int, float, etc), the value of the variable cannot be changed.  Example 1: Usage of final with primitive datatype Java Code // Java Program to illustrate Use of Final Keyword // With Primitive Dataty
2 min read
Final Arrays in Java
As we all know final variable declared can only be initialized once whereas the reference variable once declared final can never be reassigned as it will start referring to another object which makes usage of the final impracticable. But note here that with final we are bound not to refer to another object but within the object data can be changed
4 min read
Comparison of static keyword in C++ and Java
Static keyword is used for almost the same purpose in both C++ and Java. There are some differences though. This post covers similarities and differences of static keyword in C++ and Java. Similarities between C++ and Java for Static KeywordStatic data members can be defined in both languages.Static member functions can be defined in both languages
6 min read
Using the super Keyword to Call a Base Class Constructor in Java
We prefer inheritance to reuse the code available in existing classes. In Java, Inheritance is the concept in which one class inherits the properties of another class. In the below example there are two classes Programming and DP while Programming is Parent class and DP is child class. From the main class, we have created an object of DP i.e. child
5 min read
super keyword for Method Overloading in Java
We use Method overloading to use a similar method for more than one time. This can be achieved by using different parameters in the signature. In the below example a class GFG with three similar methods is available, though the three methods are overloaded they are provided with different parameters. The object of the class GFG calls a method with
4 min read
var keyword in Java
The var reserved type name (not a Java keyword) was introduced in Java 10. Type inference is used in var keyword in which it detects automatically the datatype of a variable based on the surrounding context. The below examples explain where var is used and also where you can't use it. 1. We can declare any datatype with the var keyword. Java Code /
4 min read
Usage of Enum and Switch Keyword in Java
An Enum is a unique type of data type in java which is generally a collection (set) of constants. More specifically, a Java Enum type is a unique kind of Java class. An Enum can hold constants, methods, etc. An Enum keyword can be used with if statement, switch statement, iteration, etc. enum constants are public, static, and final by default.enum
4 min read
Usage of Break keyword in Java
Break keyword is often used inside loops control structures and switch statements. It is used to terminate loops and switch statements in java. When the break keyword is encountered within a loop, the loop is immediately terminated and the program control goes to the next statement following the loop. When the break keyword is used in a nested loop
6 min read
Super Keyword in Java
The super keyword in Java is a reference variable that is used to refer to parent class when we're working with objects. You need to know the basics of Inheritanceand Polymorphism to understand the Java super keyword.  The Keyword "super" came into the picture with the concept of Inheritance. In this article, we gonna covers all about super in Java
8 min read
Protected Keyword in Java with Examples
Access modifiers in Java help to restrict the scope of a class, constructor, variable, method, or data member. There are four types of access modifiers available in java. The access of various modifiers can be seen in the following table below as follows:  The protected keyword in Java refers to one of its access modifiers. The methods or data memb
5 min read
Practice Tags :