Experiment 10: Constant Declarations


 

The only problem with our declarations of pi and twoPi in the preceding experiment is that their values are constants (i.e., pi should never change during program execution), and the preceding declaration declares their names as variables -- objects whose values can vary as the program executes.

To illustrate this idea, let's pretend to make a mistake. Place the following assignment statement somewhere after the declaration statement and recompile Express.java:

   pi = -1.1;

No error will be generated, because we are simply changing the value of a variable, which is a perfectly valid operation.

To avoid such problems, alter the declaration statement in Express.java so that it appears as follows:

   final double PI = 3.14159,
                TWO_PI = 2.0 * PI;

Then alter the assignment and other statements to use the new names:

   PI = -1.1;

and recompile. Record the error message generated in the space below:





So whenever you have an object in a program whose value should not change, precede its declaration with the keyword final. Then, if you mistakenly try and change its value, the compiler will alert you to your mistake.

By convention, the names of Java constant objects are whole words, given in all upper-case letters, with underscores used to separate multiple words.

Using this information, construct error-free constant declarations for the identifiers:

SPEED_OF_LIGHT, containing the value 3.0 * 108:




MAXIMUM_SCORE and MINIMUM_SCORE, containing the integer values 0 and 100, respectively:




MIDDLE_INITIAL, containing the appropriate character for your middle initial:




FOREVER, set to true.




Use Express.java to verify that your constant declarations are correct. When they are, proceed.

The type of an expression is the type of value it produces when evaluated. When declaring variables or constants, the type used to declare the identifier should always be the same as the type of value that is to be stored in that identifier's storage.

You should now know how to declare Java constant objects, and the difference between them and Java variable objects.


Back to the Exercise List

Forward to the Next Experiment


Back to the Table of Contents

Back to the Introduction


Copyright 2000 by Prentice Hall. All rights reserved.