whose value could be changed by an assignment 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);
while (hi < MAX) {
System.out.println(hi);
hi = lo + hi;
lo = hi - lo;
}
}
}
Modifying the maximum value now requires only one change, in one part of the program, and it is clearer
what the loop condition is actually testing.
You can group related constants within a class. For example, a card game might use these constants:
class Suit {
final static int CLUBS = 1;
final static int DIAMONDS = 2;
final static int HEARTS = 3;
final static int SPADES = 4;
}
To refer to a static member of a class we use the name of the class followed by dot and the name of the
member. With the above declaration, suits in a program would be accessed as Suit.HEARTS,
Suit.SPADES, and so on, thus grouping all the suit names within the single name Suit. Notice that the
order of the modifiers final and static makes no differencethough you should use a consistent order. We
have already accessed static fields in all of the preceding examples, as you may have realizedout is a
static field of class System.
Groups of named constants, like the suits, can often be better represented as the members of an enumeration
type, or enum for short. An enum is a special class with predefined instances for each of the named constants
the enum represents. For example, we can rewrite our suit example using an enum:
enum Suit { CLUBS, DIAMONDS, HEARTS, SPADES }
Each enum constant is a static field that refers to the object for that valuesuch as Suit.HEARTS. By
representing each named constant as an object rather than just an integer value, you improve the type-safety
and so the robustness, of your program. Enums are covered in detail in Chapter 6.