Variables are useful when you need to store information that can be changed as program runs. However, there may be certain situations in the program in which the value of variable should not be allowed to modify. This is accomplished using a special type of variable known as final variable. The final variable also called constant variable. It is a variable with a value that cannot be modified during the execution of the program.
To declare a final variable, use the final keyword before the variable declaration and initialize it with a value. Its syntax is
final datatype varName = value;
For example:
final double PI = 3.141592;
This statement declares a variable PI of type double which is initialized to 3.141592, that cannot be modified. If an attempt is made to modify a final variable after it is initialized, the compiler issues an error message “cannot assign a value to final variable PI”.
You can also defer the initialization of final variable; such a final variable is known as blank final. However, it must be initialized before it is used.
Final variables are beneficial when one need to prevent accidental change to method parameters and with variables accessed by anonymous class.
Now consider a program to calculate the area of the circle,
// Area of the Circle
class area { public static void main(String args[]) { int r=10; //initializing radius final double PI=30141592; // final variable double area; area = PI * r *r; System.out.println("Area of Circle is : " +area); } }