Java Reference
In-Depth Information
We will fully explain the modifiers
public static final
later in this topic , but
we can now explain most of what they mean. The part
int
BRANCH_COUNT = 10;
simply declares
BRANCH_COUNT
as a variable and initializes it to
10
. The words that precede
this modify the variable
BRANCH_COUNT
in various ways. The word
public
says there
are no restrictions on where you can use the name
BRANCH_COUNT
. The word static will
have to wait until Chapter 5 for an explanation, but be sure to include it.The word
final
means that the value
10
is the
final
value assignment to
BRANCH_COUNT
, or, to phrase it
another way, that the program is not allowed to change the value of
BRANCH_COUNT
.
Naming Constants
The syntax for defining a name for a constant outside of a method, such as a name for a
number, is as follows:
SYNTAX
public static final
Type Variable = Constant
;
EXAMPLE
public static final int
MAX_SPEED = 65;
public static final double
MIN_SIZE = 0.5;
public static final
String GREETING = "Hello friend!";
public static final char
GOAL = 'A';
Although it is not required, it is the normal practice of programmers to spell named constants
using all uppercase letters with the underscore symbol used to separate “words.”
Java Spelling Conventions
In Java, as in all programming languages, identifiers for variables, methods, and
other items should always be meaningful names that are suggestive of the identifiers'
meanings. Although it is not required by the Java language, the common practice of
Java programmers is to start the names of classes with uppercase letters and to start the
names of variables, objects, and methods with lowercase letters. Defined constants are
normally spelled with all uppercase letters and underscore symbols for “punctuation,”
as we did in the previous subsection, “Naming Constants.”
For example,
String
,
FirstProgram
, and
JOptionPane
are classes, although we
have not yet discussed the last one. The identifiers
println
,
balance
, and
readLine
should each be either a variable, an object, or a method.
Since blanks are not allowed in Java identifiers, “word” boundaries are indicated by
an uppercase letter, as in
numberOfPods
. Since defined constants are spelled with all
uppercase letters, the underscore symbol is used for “word” boundaries, as in
MAX_SPEED
.
The identifier
System.out
seems to violate this convention, since it names an
object but yet begins with an uppercase letter. It does not violate the convention, but
the explanation hinges on a topic we have not yet covered.
System
is the name of a