Java Reference
In-Depth Information
If the value should never change during a program's runtime, you can use a type of vari-
able called a constant. A constant , which also is called a constant variable , is a variable
with a value that never changes. This might seem like an oxymoron, given the meaning
of the word “variable.”
Constants are useful in defining shared values for the use of all methods of an object. In
Java, you can create constants for all kinds of variables: instance, class, and local.
To declare a constant, use the final keyword before the variable declaration and include
an initial value for that variable, as in the following:
final float PI = 3.141592;
final boolean DEBUG = false;
final int PENALTY = 25;
In the preceding statements, the names of the constants are capitalized: PI , DEBUG , and
PENALTY . This is a convention adopted by many Java programmers that makes it clear
you're using a constant instead of a variable.
Constants can be handy for naming various states of an object and then testing for those
states. Suppose you have a program that takes directional input from the numeric keypad
on the keyboard—push 8 to go up, 4 to go left, and so on. You can define those values as
constant integers:
final int LEFT = 4;
final int RIGHT = 6;
final int UP = 8;
final int DOWN = 2;
Constants often make a program easier to understand. To illustrate this point, consider
which of the following two statements is more informative as to its function:
guide.direction = 4;
guide.direction = LEFT;
Today's first project is a Java application that creates several variables, assigns them ini-
tial values, and displays two of them as output. The full source code is in Listing 2.1.
LISTING 2.1
The Full Text of Variables.java
1: public class Variables {
2:
3: public static void main(String[] arguments) {
4: final char UP = 'U';
Search WWH ::




Custom Search