Java Tutorial – 17 – Constants
A variable in Java can be made into a constant by adding the final
keyword before the data type. This modifier means that the variable cannot be reassigned once it has been set, and any attempts to do so will result in a compile-time error.
Local constants
A local constant must always be initialized at the same time as it is declared. The Java naming convention for constants is to use all uppercase letters and to separate the words with underscores.
final double PI = 3.14;
Constant fields
Class and instance variables can also be declared as final
.
class MyClass { final double E = 2.72; static final double C = 3e8; }
In contrast to local constants, constant fields cannot only be assigned at declaration. A constant instance field can optionally be assigned in a constructor, and a constant static field may be assigned by using a static initialization block. These alternative assignments can be useful if the constant’s value needs to be calculated and does not fit on a single code line.
class MyClass { final double E; static final double C; public MyClass() { E = 2.72; } static { C = 3e8; } }
Constant method parameters
Another place where the final
modifier may be applied is to method parameters to make them unchangeable.
void f(final int A) {}
Compile-time and run-time constants
As in most other languages, Java has both compile-time and run-time constants. However, only class constants can be compile-time constants in Java, and only if their value is known at compilation. All other uses of final
will create run-time constants. With compile-time constants the compiler will replace the constant name everywhere in the code with its value. They are therefore faster than run-time constants, which are not set until the program is run. Run-time constants, however, can be assigned dynamic values that can change from one program run to the next.
class MyClass { final double E = 2.72; // run-time constant final static double C = 3e8; // compile-time constant final static int RND = (new java.util.Random()).nextInt(); // run-time constant }
Constant guideline
In general, it is a good idea to always declare variables as final
if they do not need to be reassigned. This ensures that the variables will not be changed anywhere in the program by mistake, which in turn helps to prevent bugs.