This lesson is about the keyword final. You use the keyword final to make a variable constant so that it can be assigned a value only once. Variables are declared final be using the keyword final while declaring them. For example,

final double  PI=3.1416;

In the above example, the PI is declared final and it can not be changed afterwards in the program.
*It is a convention to name the final variables in camel case.

A final variable may be accessed any number of times in a program but any attempt to change it will cause an error. The following example shows a final variable being created and accessed:

The following code tries to change a final variable and as a result, an exception (error) is thrown:

Methods and classes can also be declared final. 
  • If a method is declared final, it can not be overridden. We will learn about method overriding in an upcoming lesson.
  • If a class is declared final, its subclasses can not be created. We will learn about creating subclasses in an upcoming lesson
One of the most annoying error in programming is the logical error. A syntax error is easily caught by the IDE as it underlines it and gives a warning but a logical error is much difficult to catch. In this case, the syntax is correct but the programmer makes a logical mistake while coding. One of the mistakes is changing the value of a variable accidentally that was not meant to be changed. Making such variables final will help us decrease the chance of some mistake. If we try to change the value of the final variable, the IDE will point the mistake so that we can easily correct it. It saves the hectic effort of searching for the error yourself.