The Final Keyword In Java

One of the tricky aspects in Java is understanding the final keyword usage. This keyword can be used across multiple context But the rules for all of these are not exactly the same but you can kind of guess. Let us understand them all in detail.

When used to modify a variable

When you have a variable value which never changes for the duration of the program, you can use final keyword. A final variable can be used for all the below types

  • as a final instance variable
  • as final static variable
  • as final local variable inside any type of code block, for e.g., a method, for loop etc..
final int NUMBER_OF_STATES = 50;

final String COUNTRY;

COUNTRY = "USA"

Final modifier added to an instance or member variable

You can add final when a variable is declared or declared and assigned. In these cases, the following rules apply:

  • A final variable can be declared and assigned at the same time (NUMBER_OF_STATES example above) then the value cannot be changed again in the program. This is the most optimal way of using it.
  • A final variable can be declared once and then initialized later in another statement. The following rules apply:

    • If used as an instance variable, then it can be assigned inside a constructor.
    • If used for a static variable then it can assigned inside a static initializer block
    • If used on a local variable, then it can assigned within the specific code block.

    But once assigned, the value cannot be changed. Variables declared final must be initialized at one of the above constructs, otherwise compile-time error is thrown

  • Naming convention for final variables are all upper case with underscores separating the words.
  • These are also called constants as they do not change once assigned.
  • Most often these final variables are also good candidates for making them static as well. Remember when a variable is declared static only one copy of that variable is kept in memory.

Final as a local variable in method signature or inside any block of code

Final variables are optimized for better performance. You will see many methods declaring their arguments final when those variables should never be changed inside the body of the method.

The below code is a perfectly valid usage of final as in every iteration a new variable i is declared which is local to the for block and that variable is made final.

 for (final int i : arr) {
     System.out.print(i + " "); 
 }

Note: If the final variable is pointing to an object, then the state of the object can change but the final variable cannot be assigned to another object.

For e.g, the customer object that is created can be updated with different state values but you cannot instantiate another customer object and reassign the variable. The below program is allowed as we are only changing the state.


final Customer customer = new Customer();
customer.setName("Foo");

// customer = new Customer() --- this is not allowed

When used to modify a class declaration

When a class is declared with final keyword, it cannot have children, ie., cannot be extended or inherited.

The below code is illegal in Java


final class A {
     // methods and fields
}
// The following class is illegal.
class B extends A { 
    // A is final so COMPILE-ERROR! A cannot be inherited by another class.
}

When used to modify a method signature

When a method is declared with final keyword, it is called a final method. A final method cannot be overridden by any children.


class A {
    public final void mymethod() {
        // this method cannot be overridden by any children
    }
}
// The following method override is illegal
class B extends A { 
    public void mymethod() {
          // this method definition is illegal
    }
}

The final property violations are compile time errors.

results matching ""

    No results matching ""