final keyword in java with examples

final keywords are applied to variables, method, and class. and the meaning is once the final is applied, its value or state cannot be changed.

what are the final variables in java?

if we apply the final keyword to fields or member variables, the variables are tread as constants, which means once the variable is created, and assigned with value, The value can not be changed.

final int value=20;
// Gives compile time error for the below line of code
value=40;

I the above example,

  • An initialized final variable with value=20
  • next line, change the value to 40
  • Compiler throws an error Cannot assign a value to final variable 'value'

So you have to use the fields as final whenever the value of the field cannot be changed once it is initialized.

Let’s see final objects

  final ArrayList<String> strs = new ArrayList<String>();
        strs.add("hello"); // no error
        strs = null; // an error
  • In the above example, the final ArrayList variable is created
  • Changed the state of an ArrayList by adding add method, This is accepted and the final object can be mutated.
  • next line, Change the reference with null, It gives a compilation error as final references are not assigned to the null or new object

what are the final methods in java?

methods can also define with the final keyword. A final method does not override in a subclass

following is the usage of a final method

class SuperClass {
 public final void method1() {

 }

 public int method2() {
  return 0;

 }
}

class SubClass extends SuperClass {
 // the following method throws Compile time exception as this method has
 // been declared in Superclass.Final methods ca
 public final void method1() {

 }

 // This works fine
 public int method2() {
  return 0;

 }

what is a final class in java?

if we mark the class as final, the class does not extend by another class.

This makes the class as some specific class that is secure. Most of the classes are in java.lang.Math classes are final classes. The compiler will throw an error if we extend the final class.

Here is the example for the final class

public final class SuperClass {

}

// the following class throws Compile time exception as the Superclass declared
// as final

class SubClass extends SuperClass {

}


Final as an argument to the method

You can also pass the final keyword parameters to the methods. That means the parameters can not be changed and are local to the method.

public void getValue(final int i){

 }

Does final local variables increase performance

declaring final local variables allows the compiler to optimize the code statically and improve faster