Java Constants (final)
Constants (final keyword)
When you do not want a variable's value to change, use the final
keyword.
A variable declared with final
becomes a constant, which means unchangeable and read-only:
Example
final int myNum = 15;
myNum = 20; // Error: cannot assign a value to final variable 'myNum'
When to Use final?
You should declare variables as final
when their values
should never change.
For example, the number of minutes in an hour will always be 60, and your birth
year will never change:
Note: By convention, final variables in Java are usually
written in upper case (e.g. BIRTHYEAR
). It is not required, but useful
for code readability and common for many programmers.