See also: The Java® Language Specification Section 4.12.4
Strictly speaking, a Java constant variable is defined as a:
The first two requirements should be clear. Here's an example of a primitive, static, final variable which is not a constant variable because it is not initialized with a compile-time constant value:
public class FinalVarInitializedAtRuntime
{
public static final long SESSION_KEY = makeSessionKey();
// ...
private static long makeSessionKey()
{
long mask = 0xFF00FF00FF00FF00L;
long millis = System.currentTimeMillis();
long key = millis ^ mask;
return key;
}
}
One of the principal reasons for using constant Variables is that a constant variable can be extracted from a class without first loading the class. This is a great advantage because loading a class is an expensive, time-consuming operation.
Attentive Java programmers follow the convention that constant variable identifiers are not to include lowercase characters. Should that convention apply to the SESSION_KEY variable above, since it's not a constant variable as defined by the Java Language Specification? What about the ONE and TEN constants in the BigInteger class, which are not primitives? What about private identifiers, which will never be extracted from a class without first loading the class? The advice I give to my students is: "If it's public, static, and final, treat it as a constant variable. If it's private, do whatever seems logical.