(^58) | Java Syntax and Semantics, Classes, and Objects
As shown in the preceding code, many Java programmers capitalize the entire identifier of
a named constant and separate the English words with an underscore. The idea is to help the
reader quickly distinguish between variable names and constant names when they appear
in the middle of code. In one case, we split the declaration across two lines, placing the string
literal on the line following the definition of the identifier. This kind of break works in Java,
but remember that we cannot split the string literal itself across two lines.
It’s a good idea to add comments to constant declarations as well as variable declarations.
For example:
finalString STARS = “****”; // Row of stars to use as a separator
final char BLANK = ‘ ‘; // A single blank
Fields The similar appearance of variable and constant declarations in Java is no coinci-
dence. Java doesn’t actually distinguish between the declarations of named constants and
variables because both are considered just different kinds of fields. A named constant is
merely a field that is given an initial value, together with the modifier final, which says that
the value can never change. If we extend the template for a variable declaration to include
the syntax necessary to give the variable an initial value and add the keyword finalto the
list of modifiers, then we have a generic template for a field declaration in Java:
The following declarations are legal:
finalString WORD1 = “Introduction to “;
String word3 = “Programming and Problem Solving “;
finalString WORD5 = “with Java”;
private
public
final
Modifiers
Modifiers Type-Name Identifier = Literal-Value^
Field-Declaration
, Identifier = Literal-Value ;