misty dark cloudy desert with snow bridge

1.8 Java | Named Constants

A Named Constant is an identifier that represents a permanent value. The value of a variable may change during the execution of a program; but a Named Constant (or just Constant) represents permanent data that never changes (for example, π is a constant) depending on the type of Java “constant”.

Final vs. Static Final

There are 2 types of Java “constants”. final and static final. The syntax for declaring the lone final constant is:

The lone final constant only forces a variable value to be permanent in a single class instance.

The syntax for declaring static final is:

The constants static final forces a variable value to be permanent in all class instances.

Example

A Java named constant can be declared and initialized in the same statement or in separate statements. The word final is a Java keyword for declaring a constant. For example:

Let’s say that in the above example you add the statement:

to re-assign the value of PI. But the benefit of using the constant declaration final is that the Java program will not allow you to change the value of a constant:

Java final declaration reuse constant error

Another benefit is that you only have to change the value of the constant from a single location.


What's Your Opinion?