Programming exercises
Chapter 3 Expressions
3.2 Constants and variables
The two simplest types of terms in an expression are constants and variables. Constants appear when you need to use an explicit value that doesn’t change over the course of the program. Variables are placeholders for data that can change during execution. The sections that follow show you how to write constants and variables and detail the rules that Java imposes on their specification.
Constants
When you write a formula in mathematics, some symbols in the formula typically represent unknown values while other symbols represent constants whose values are known. Consider, for example, the mathematical formula for computing the circumference (C) of a circle given its radius (r):
C = 2π r
To translate this formula into a expression, you would use variables to record the radius and circumference. These variables change depending on the data. The values 2 and π, however, are constants—explicit values that never change. The value 2 is an integer constant, and the value π is a real number constant, which would be represented in a program by a floating-point approximation, such as 3.14159265358979323846. Because constants are an important building block for constructing expressions, it is important to be able to write constant values for each of the basic data types.
• Integer constants. To write an integer constant as part of a program or as input data, you simply write the digits that make up the number. If the integer is negative, you write a minus sign before the number, just as in mathematics. Commas are never used. Thus, the value one million must be written as 1000000 and not as 1,000,000.
• Floating-point constants. Floating-point constants in Java are written with a decimal point. Thus, if 2.0 appears in a program, the number is represented internally as a floating-point value; if the programmer had written 2, this value would be an integer.
Floating-point values can also be written in a special programmer’s style of scientific notation, in which the value is represented as a floating-point number multiplied by a integral power of 10. To write a number using this style, you write a floating-point number in standard notation, followed immediately by the letter E and an integer exponent, optionally preceded by a + or - sign. For example, the speed of light in meters per second is approximately
2.9979 x 108
which can be written in Java as 2.9979E+8
where the E stands for the words times 10 to the power.
Boolean constants and character constants also exist and are described in subsequent chapters along with their corresponding types.
There is, however, one additional form of constant that you need to know about, even though it is not a primitive type:
• String constants. You write a string constant in Java by enclosing the characters that comprise the string in double quotation marks. For example, the very first example of data used in this text was the string
"hello, world"
in the HelloProgram example from Chapter 2. This string consists of the characters shown between the quotation marks, including the letters, the comma, and the space. The quotation marks are not part of the string but serve only to mark its beginning and end. There are several additional rules for writing string constants that allow you to include special characters (such as quotation marks) within the string. These rules are described in detail in Chapter 8.
Variables
A variable is a placeholder for a value and has three important attributes: a name, a
value, and a type. To understand the relationship of these attributes, it is easiest to think of a variable as a box with a label attached to the outside. The name of the variable appears on the label and is used to tell the different boxes apart. If you have three boxes (or variables), you can refer to a particular one using its name. The value of the variable corresponds to the contents of the box. The name on the label of the box never changes, but you can take values out of a box and put new values in as often as you like. The type of the variable indicates what kind of data values can be stored in the box. For example, if you have a box designed to hold values of type int, you cannot put values of type string into that box.
Names in Java—for variables as well as other sorts of things such as classes and methods—are called identifiers. Identifiers must be constructed according to the following rules:
1. Identifiers must start with a letter or the underscore character (_). In Java, uppercase and lowercase letters appearing in an identifier are considered to be different, so the names ABC, Abc, and abc refer to three separate identifiers.
2. All other characters in an identifier must be letters, digits, or the underscore. No spaces or other special characters are permitted. Identifiers can be of any length.
3. Identifiers must not be one of the following reserved words, which are names that Java defines for a specific purpose:
abstract else interface super
boolean extends long switch
break false native synchronized
byte final new this
case finally null throw
catch float package throws
char for private transient
class goto protected true
const if public try
continue implements return void
default import short volatile
do instanceof static while
double int strictfp
In addition, good programming style requires two more rules, as follows:
4. Identifiers should make obvious to the reader the purpose of the variable, class, or method. Although names of friends, expletives, and the like may be legal according to the other rules, they do absolutely nothing to improve the readability of your programs.
5. Identifiers should match the case conventions that have become standard in Java. In particular, variable names should begin with a lowercase letter; class names should begin with an uppercase letter. Thus, n1 is appropriate as the name of a variable, and HelloProgram is appropriate as the name of a class. Each additional English word appearing in the name is typically capitalized to improve readability, as in the variable name numberOfStudents. Names that are used as constants, which are discussed in the section entitled “Named constants” later in this chapter, use only uppercase letters and separate words with underscores, as in PLANCKS_CONSTANT.
Declarations
As noted in the discussion of the Add2Integers program in Chapter 2, you must explicitly specify the data type of each variable when you introduce it into a program. This process is known as declaring the variable. The syntax for declaring a variable is expressed in the following line:
type identifier = expression;
Syntax for declarations:
type identifier = expression;
where:
type is the type of the variable
identifier is the name of the variable
expression specifies the initial value The code line above with its italicized pieces is an
example of a syntax template. The words in italics represent items you can fill in with anything that fits the specification of that template. In writing an assignment statement, for example, you can declare variables of any type, use any identifier to the left of the equal sign, and supply any expression on the right. The boldface items in the template—in this case the equal sign and the semicolon—are fixed. Thus, in order to write a declaration, you start with
the type name, followed by the variable name, an equal sign, an expression, and a semicolon, in that order.
When new syntactic constructs are introduced in this text, they will be accompanied by a syntax box that defines their structure, such as the one shown on the right. Syntax
boxes contain a capsule summary of the grammatical rules for Java and serve as a handy reference.
The equal sign and the expression giving the initial value are in fact optional in a variable declaration. Leaving them out, however, can often lead to programming errors because the initial value of the variable depends on the context in which it is declared. In this text, all variables declared inside methods will be given an initial value to eliminate this source of error.
Variables can be declared in several different parts of the program. The variables you have seen up to this point have all been declared inside the body of a method. (So far, that method has always been r u n, but it is legal to declare variables in any method.) Variables declared inside a method are called local variables because they are available only to that method and not to any other parts of the code. You can, however, declare variables within the definition of a class but outside of any method. Variables defined at this level are called instance variables, or ivars for short, and are stored as part of each object. Instance variables must be used with a certain amount of care, and it is probably best to avoid them until you have a chance to learn about some of the appropriate strategies in Chapter 5. There is, however, one additional style of variable declaration that is particularly important for good programming style. These variables are called class variables and, as their name suggests, are defined at the level of the class rather than at the level of a method. Unlike instance variables, class variables are associated with all objects of a particular class and not with individual objects. Class variables must also be used with care, but they are precisely the right tool for introducing names for constants, as discussed in the following section.
Named constants
As you write your programs, you will find that you will often use the same constant many times in the same program. If, for example, you are performing geometrical calculations that involve circles, the constant π comes up frequently. Moreover, if those calculations require high precision, you might actually need all the digits that fit into a value of type double, which means you would be working with the value 3.14159265358979323846. Writing that constant over and over again is tedious at best, and error-prone if you try to type it in each time by hand instead of cutting and pasting the value. It would be better if you could give this constant a name and then use it everywhere in the program. You could, of course, simply declare it as a local variable by writing
double pi = 3.14159265358979323846;
but you would then be able to use it only within the method in which it was defined. A better strategy is to declare it as a class variable like this:
private static final double PI = 3.14159265358979323846;
The keywords at the beginning of this declaration each provide some information about the nature of the declaration. The private keyword indicates that this constant can be used only within the class that defines it. It often makes more sense to declare constants to be public, but good programming practice suggests that you should keep all declarations private unless there is a compelling reason to do otherwise. The static keyword indicates that this declaration introduces a class variable rather than an instance variable. The final keyword declares that the value will not change after the variable is initialized, thereby ensuring that the value remains constant. It would not be appropriate, after all, to change the value of π (despite the fact that a bill was introduced in 1897 into the Indiana State Legislature attempting to do just that). The rest of the declaration
consists of the type, the name, and the value, as before. The only difference is that the name is written entirely in uppercase to be consistent with Java’s naming scheme.
Using named constants offers several advantages. First, it usually makes the program easier to read. More importantly, however, using constants makes the program easier to maintain. Many constants in a program specify things that might change from release to release, even though they will be constant during the execution of any program. Suppose, for example, that you were writing one of the early networking programs and decided that you needed to impose a limit—as the designers of the ARPANET did in 1969—of 127 computers (which were called hosts in the ARPANET days) that could be connected. If Java had existed in those days, you might have declared a constant that looks like this:
private static final int MAXIMUM_NUMBER_OF_HOSTS = 127;
At some later point, however, the explosive growth of networking would force you to raise this bound. That process is relatively easy if you use named constants in your programs. To raise the limit on the number of hosts to 1023, it might well be sufficient to change this declaration so that it read
private static final int MAXIMUM_NUMBER_OF_HOSTS = 1023;
If you adopted this approach and used MAXIMUM_NUMBER_OF_HOSTS everywhere in your program in which you needed to refer to that maximum value, then making this simple change would automatically propagate to every part of the program in which this name was used. The situation would be entirely different if you had written the constant 127 everywhere instead. In that case, you would need to search through the entire program and change all instances of 127 used for this purpose to the larger value. And if you missed one, you would likely have a very hard time tracking down the bug.