Java Reference
In-Depth Information
separated using the underscore character. For example, the constant describing
the maximum occupancy of a theater could be declared as follows:
final int MAX_OCCUPANCY = 427;
The compiler will produce an error message if you attempt to change the value
of a constant once it has been given its initial value. This is another good reason
to use constants. Constants prevent inadvertent coding errors because the only
valid place to change their value is in the initial assignment.
There is a third good reason to use constants. If a constant is used throughout
a program and its value needs to be modified, then you have to change it in only
one place. For example, if the capacity of the theater changes (because of a reno-
vation) from 427 to 535, then you have to change only one declaration, and all
uses of MAX_OCCUPANCY automatically reflect the change. If the literal 427 had been
used throughout the code, each use would have to be found and changed. If you
were to miss any uses of the literal value, problems would surely arise.
SELF-REVIEW QUESTIONS (see answers in Appendix N)
SR 2.9 What is a variable declaration?
SR 2.10 Given the following variable declarations, answer each question.
int count = 0, value, total;
final int MAX_VALUE = 100;
int myValue = 50;
a. How many variables are declared?
b. What is the type of these declared variables?
c. Which of the variables are given an initial value?
d. Based on the above declarations, is the following assignment state-
ment legal? Explain.
myValue = 100;
e. Based on the above declarations is the following assignment state-
ment legal? Explain.
MAX_VALUE = 50;
SR 2.11 Your program needs a variable of type int to hold the number of CDs
in a music collection. The initial value should be zero. Write a declara-
tion statement for the variable.
SR 2.12 Your program needs a variable of type int to hold the number of feet
in a mile (5,280). Write a declaration statement for the variable.
SR 2.13 Briefly describe three reasons for using a constant in a program instead
of a literal value.
 
Search WWH ::




Custom Search