final keyword in Java programming language is used as a non-access modifier. final can be applied to a variable, method or a class.

final variables

A variable, which is defined as final can be assigned only once after declaration. The variable is treated as constant, whose value can not be modified after assigning a value to it. If a final variable is a reference variable, like an Array or Collection, it can not be used to reference another variable. However internal state of the final reference variable can be changed. i.e, we can add to or remove elements from a final Array or Collection. It is good practice to use uppercase letters while declaring a final variable. final variables are generally used to define constants, whose value does not change through out program execution.


// final variable with assignment
final int CODE = 5;

// blank final variable
final String TEXT;

// static block to assign value to final variable
  TEXT = “My Final Text”;

In above example we can see that the variable can be declared as final and value can be assigned only once. We can initialize the final variables while declaration of the variable, inside class constructor or using class initialization block.

final reference variable Example:

public class Test {
    public static void main(String[] args) {
        final int a[] = {1, 2, 3};
        int b[] = {4, 5 ,6};
        a = b; //Compilation error will be thrown here
        for(int x=0; x < a.length; x++)

In above example, we can modify the values of array a[], but we can not make it refer to another array b[]. i.e, once the final array(a[]) is assigned, it can not be used to refer anything else.

final class

A Java class, which is declared as final prevents it from extending using another class. String class in Java is a final class, there by prevents it from  getting extended by other classes.

Abstract class can not be declared as final. Abstract classes are incomplete classes, which should be extended by other classes and should be provided with implementation for the defined abstract methods. Declaring abstract class to final gives a compilation error.

String, Wrapper classes(Integer, Long, etc) are declared as final classes in Java.

final method

If a method is declared as final, it can not be overridden. That means, you can extend the class which is having a final method, but you can not override the final method.

An abstract method can not be declared as final, because abstract methods are not complete methods and they should be implemented by the class, which extends the class, which is having abstract method.

We can not make a constructor method final. This will throw a compilation error.