Java Reference
In-Depth Information
explains the 0.05, and so on. However, the next person who needs to maintain this
code may live in another country and may not know that a nickel is worth five cents.
Thus, it is a good idea to use symbolic names for all values, even those that appear
obvious. Here is a clearer version of the computation of the total:
140
141
double quarterValue = 0.25;
double dimeValue = 0.1;
double nickelValue = 0.05;
double pennyValue = 0.01;
payment = dollars + quarters * quarterValue + dimes
* dimeValue
+ nickels * nickelValue + pennies *
pennyValue;
There is another improvement we can make. There is a difference between the
nickels
and
nickelValue
variables. The
nickels
variable can truly vary over
the life of the program, as we calculate different payments. But
nickelValue
is
always 0.05.
A
final
variable is a constant. Once its value has been set, it cannot be changed.
In Java, constants are identified with the keyword
final
. A variable tagged as
final
can never change after it has been set. If you try to change the value of a
final
variable, the compiler will report an error and your program will not compile.
Many programmers use all-uppercase names for constants (
final
variables), such as
NICKEL_VALUE
. That way, it is easy to distinguish between variables (with mostly
lowercase letters) and constants. We will follow this convention in this topic.
However, this rule is a matter of good style, not a requirement of the Java language.
The compiler will not complain if you give a
final
variable a name with lowercase
letters.
Use named constants to make your programs easier to read and maintain.
Here is an improved version of the code that computes the value of a payment.
final double QUARTER_VALUE = 0.25;
final double DIME_VALUE = 0.1;
final double NICKEL_VALUE = 0.05;