Constants

index
BASIC

A constant is a name that has a value. Unlike a variable, a constant always has the same value, which is typically specified in its declaration. For example:

final int DAYS_IN_A_WEEK = 7;

The keyword final indicates that the value, once specified, cannot be changed. Attempting to do so will result in a syntax error.

Java provides some built-in constants, such as Math.PI and Math.E.

STYLE

Constants help avoid the use of "magic numbers"--numbers in code whose meaning may not be absolutely clear. For example,

if (width > 1024) width = 1024;

isn't as easy to understand as

if (width > SCREEN_WIDTH) width = SCREEN_WIDTH;

However, it is silly to name a constant after its value, for example,

final int TWELVE = 12;

because this does nothing to improve the clarity of your code.

There are strict conventions for constant names:

Many kinds of things in Java have names, not just constants. Proper naming and capitalization helps the experienced Java programmer know what kind of thing is being named.