Programming and Problem Solving with Java

(やまだぃちぅ) #1
2.1 The Elements of Java Programs | 57

In Java, as in mathematics, a constant is something whose value never
changes. When we use the actual value of a constant in a program, we are using
a literal value(or literal).
An alternative to the literal constant is the named constant(or symbolic con-
stant), which is introduced in a declaration statement. A named constant is just
another way of representing a literal value. Instead of using the literal value di-
rectly our code, we give the literal value a name in a declaration statement, then
use that name in the code. For example, we can write an instruction that prints
the title of this book using the literal string ”Introduction to Programming and Problem
Solving with Java”. Or we can declare a named constant called BOOK_TITLEthat
equals the same string and then use the constant name in the instruction. That
is, we can use either


“Introduction to Programming and Problem Solving with Java ”


or


BOOK_TITLE


in the instruction.
Using the literal value of a constant may seem easier than giving it a name and then re-
ferring to it by that name. In fact, named constants make a program easier to read, because
they make the meaning of literal constants clearer. Also, named constants make it easier to
change a program later on.
The syntax template for a constant declaration is similar to the template for a variable
declaration:


The only difference is that we must include the modifier final, a reserved word, and follow
the identifier with an equals sign (=) and the value to be stored in the constant. The finalmod-
ifier tells the Java compiler that this value is the last and only value that this field should have.
The following are examples of constant declarations:


finalString STARS = “****”;
final char BLANK =‘ ‘;
finalString BOOK_TITLE =
“Introduction to Programming and Problem Solving with Java”;
finalString MESSAGE = “Error condition”;


Modifiers final Type-Name Identifier = Literal-Value^ ;

Constant-Declaration

Literal value Any constant
value written in Java
Named constant (symbolic
constant) A location in mem-
ory, referenced by an identifier,
that contains a data value that
cannot be changed
Free download pdf