Java Reference
In-Depth Information
6
public static void
main(String[] args)
7
{
8
final int
ARRAY_LENGTH
=
10
;
// declare constant
int
[] array =
new
int
[
ARRAY_LENGTH
];
// create array
9
10
11
// calculate value for each array element
12
for
(
int
counter =
0
; counter < array.length; counter++)
13
array[counter] =
2
+
2
* counter;
14
15
System.out.printf(
"%s%8s%n"
,
"Index"
,
"Value"
);
// column headings
16
17
// output each array element's value
18
for
(
int
counter =
0
; counter < array.length; counter++)
19
System.out.printf(
"%5d%8d%n"
, counter, array[counter]);
20
}
21
}
// end class InitArray
Index Value
0 2
1 4
2 6
3 8
4 10
5 12
6 14
7 16
8 18
9 20
Fig. 7.4
|
Calculating the values to be placed into the elements of an array. (Part 2 of 2.)
Line 8 uses the modifier
final
to declare the constant variable
ARRAY_LENGTH
with the
value
10
. Constant variables must be initialized
before
they're used and
cannot
be modified
thereafter. If you attempt to
modify
a
final
variable after it's initialized in its declaration,
the compiler issues an error message like
cannot assign a value to final variable
variableName
Good Programming Practice 7.2
Constant variables also are called
named constants
. They often make programs more
readable than programs that use literal values (e.g.,
10
)—a named constant such as
ARRAY_LENGTH
clearly indicates its purpose, whereas a literal value could have different
meanings based on its context.
Good Programming Practice 7.3
Multiword named constants should have each word separated from the next with an un-
derscore (
_
) as in
ARRAY_LENGTH
.
Common Programming Error 7.4
Assigning a value to a
final
variable after it has been initialized is a compilation error.
Similarly, attempting to access the value of a
final
variable before it's initialized results in
a compilation error like, “
variable
variableName
might
not
have
been
initialized
.
”