final variables

Java does not reserve the keyword constant to create constants. However, in Java you can prefix a variable declaration with the keyword final to make its value unchangeable. You can make both local variables and class fields final.

For example, the number of months in a year never changes, so you can write:

final int numberOfMonths = 12;

As another example, in a class that performs mathematical calculation, you can declare the variable pi whose value is equal to 22/7 (the circumference of a circle divided by its diameter, in math represented by the Greek letter ?).

final float pi = (float) 22 / 7;

Once assigned a value, the value cannot change. Attempting to change it will result in a compile error.

Note that the casting (float) after 22 / 7 is needed to convert the value of division to float. Otherwise, an int will be returned and the pi variable will have a value of 3.0, instead of 3.1428.

Note

You can also make a method final, thus prohibiting it from being overridden in a subclass.