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 if we try to so it will result in a compiler
error. A local constant such as this must therefore always be initialized at the same
time as it is declared. Class and instance variables can also be declared
as final. In contrast to local constants, these two cannot only be assigned at declaration.
An instance constant can alternatively be assigned in a constructor. And a class constant
may be assigned using a static initialization block. These alternative assignments can be
useful if we want to calculate the constant value and if that calculation doesn’t fit
on a single code line. Another place where we may apply the final
modifier is to method parameters to make them unchangeable. Note that the naming convention
for constants in Java is to use all uppercase letters and to separate the words by underscores. In general it is a good idea to always declare
variables as final if they don’t need to be reassigned, because this makes sure that
the variables won’t be changed anywhere in program by mistake and this helps to prevent
bugs. As in most other languages Java has both compile-time
and run-time constants. However, in Java only class constants can be compiler-time and only
if their value is known at compilation. All other uses of final will create run-time constants.
With compiler-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.

Tags: , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , ,


Leave a Reply

Your email address will not be published. Required fields are marked *