Java Reference
In-Depth Information
To allocate memory, we use Java's declaration statements. The syntax to declare a named
constant is:
static final
dataType IDENTIFIER = value;
2
In Java,
static
and
final
are reserved words. The reserved word
final
specifies that
the value stored in the identifier is fixed and cannot be changed.
In syntax, the shading indicates the part of the definition that is optional.
Because the reserved word
static
is shaded, it may or may not appear when a named
constant is declared. The section, Creating a Java Application Program, later in this
chapter, explains when this reserved word might be required. Also, notice that the
identifier for a named constant is in uppercase letters. This is because Java programmers
typically use uppercase letters for a named constant. (If the name of a named constant is a
combination of more than one word, called a run-together-word, then the words are
separated using an underscore; see the next example.)
EXAMPLE 2-11
Consider the following Java statements:
final double
CENTIMETERS_PER_INCH = 2.54;
final int
NO_OF_STUDENTS = 20;
final char
BLANK = ' ';
final double
PAY_RATE = 15.75;
The first statement tells the compiler to allocate enough memory to store a value of type
double
, call this memory space
CENTIMETERS_PER_INCH
, and store the value
2.54
in it.
Throughout a program that uses this statement, whenever the conversion formula is
needed, the memory space
CENTIMETERS_PER_INCH
can be accessed. The other state-
ments have similar meanings.
As noted earlier, the default type of floating-point numbers is
double
. Therefore, if you
declare a named constant of type
float
, then you must specify that the value is of type
float
as follows:
final float
PAY_RATE = 15.75f;
otherwise, the compiler will generate an error message. Notice that in
15.75f
, the
letter
f
at the end specifies that
15.75
is a
float
value. Recall that the memory
size for
float
values is 4 bytes; for
double
values, 8 bytes. We will mostly use
the type
double
to work with floating-point values.
Search WWH ::
Custom Search