Final Points to Remember

When a variable is declared with final keyword, its value can’t be modified, 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 internal state of the object pointed by that reference variable can be changed i.e. you can add or remove elements from final array or final collection. It is good practice to represent final variables in all uppercase, using underscore to separate words.

Initializing a final variable :
We must initialize a final variable, otherwise compiler will throw 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 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 instance-initializer block or inside constructor. If you have more than one constructor in your class then it must be initialized in all of them, otherwise compile time error will be thrown.
  3. A blank final static variable can be initialized inside static block.

When to use a final variable :
The only difference between a normal variable and a final variable is that we can re-assign 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 program.
Reference final variable :
When a final variable is a reference to an object, then this final variable is called reference final variable. Final variable cannot be re-assign. But in case of a reference final variable, internal state of the object pointed by that reference variable can be changed. Note that this is not re-assigning. This property of final is called non-transitivity.

// Java program to demonstrate
// reference final variable
class FinalReferenceUpdate
{
public static void main(String[] args)
{
// a final reference variable testVar
final StringBuilder testVar = new StringBuilder("FinalReferenceVariable");

System.out.println(testVar );

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

System.out.println(sb);
}
}
output
========================
FinalReferenceVariable
FinalReferenceVariableupdated

Comments