Java Reference
In-Depth Information
1.4. Named Constants
Constants
are values like
12
,
17.9
, and
"StringsLike This"
. Constants, or
literals as they are also known, are the way you specify values that are
not computed and recomputed but remain, well, constant for the life of a
program.
The
Fibonacci
example printed all Fibonacci numbers with a value less
than 50. The constant 50 was used within the expression of the
while
loop
and within the documentation comment describing
main
. Suppose that
you now want to modify the example to print the Fibonacci numbers with
values less than 100. You have to go through the source code and locate
and modify all occurrences of the constant 50. Though this is trivial in
our example, in general it is a tedious and error-prone process. Further,
if people reading the code see an expression like
hi< 50
they may have
no idea what the constant 50 actually represents. Such "magic numbers"
hinder program understandability and maintainability.
A
named constant
is a constant value that is referred to by a name. For
example, we may choose the name
MAX
to refer to the constant 50 in the
Fibonacci example. You define named constants by declaring fields of the
appropriate type, initialized to the appropriate value. That itself does not
define a constant, but a field whose value could be changed by an as-
signment statement. To make the value a constant we declare the field
as
final
. A
final
field or variable is one that once initialized can never
have its value changedit is
immutable.
Further, because we don't want
the named constant field to be associated with instances of the class, we
also declare it as
static
.
We would rewrite the Fibonacci example as follows:
class Fibonacci2 {
static final int MAX = 50;
/** Print the Fibonacci sequence for values < MAX */
public static void main(String[] args) {
int lo = 1;
int hi = 1;
System.out.println(lo);