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.
final int numberOfMonths = 12;
- Once assigned a value, the final value cannot change.
- Attempting to change it will result in a compile error.
final float pi = (float) 22 / 7;
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.