Programming and Problem Solving with Java

(やまだぃちぅ) #1
3.3 Declarations for Numeric Types | 107

Using Named Constants Instead of Literals


It’s a good idea to use named constants instead of literals in your code. In addition to making
your code more readable, named constants can make your applications easier to modify.
Suppose you wrote an application last year to compute taxes. In several places you used the lit-
eral 0.05, which was the sales tax rate at the time. Now the rate has gone up to 0.06. To change
your code, you must locate every mention of the literal 0.05and change it to 0.06. If 0.05is
used for some other reason—to compute deductions, for example—you also need to find each
place where it is used, figure out its purpose, and then decide whether to change it.
This process becomes much simpler if you use a named constant. Instead of using the literal
constant 0.05, suppose you had declared a named constant TAX_RATEwith a value of 0.05.To
change your code, you would simply change the declaration, setting TAX_RATEequal to 0.06. This
one modification changes all of the tax rate computations without affecting the other places
where 0.05is used.
Java allows us to declare constants with different names but the same value. If a value has
different meanings in different parts of an application, it makes sense to declare and use a con-
stant with an appropriate name for each meaning.
Named constants are also reliable—they protect us from mistakes. If you mistype the name
PIasPO, for example, the Java compiler will tell you that the namePOhas not been declared. On
the other hand, even though we recognize that the number3.14149is a mistyped version of pi
(3.14159), the number is perfectly acceptable to the compiler. It won’t warn us that anything is
wrong.

Variable Declarations


We declare numeric variables the same way that we declare charand Stringvariables, except
that we use the names of numeric types. Here are some example declarations:


int studentCount; // Number of students
int sumOfScores; // Sum of their scores
long sumOfSquares; // Sum of squared scores
double average; // Average of the scores
float deviation; // Standard deviation of scores
char grade; // Student's letter grade
String stuName; // Student's name


Given these declarations

int num;
int alpha;
doublerate;
char ch;

Free download pdf