Java Reference
In-Depth Information
4.12.4.
final
Variables
A variable can be declared
final
. A
final
variable may only be assigned to once. Declaring a
variable
final
can serve as useful documentation that its value will not change and can help
avoid programming errors.
It is a compile-time error if a
final
variable is assigned to unless it is definitely unassigned
(§16) immediately prior to the assignment.
A
blank
final
is a
final
variable whose declaration lacks an initializer.
Once a
final
variable has been assigned, it always contains the same value. If a
final
variable
holds a reference to an object, then the state of the object may be changed by operations on
the object, but the variable will always refer to the same object.
This applies also to arrays, because arrays are objects; if a
final
variable holds a reference to
an array, then the components of the array may be changed by operations on the array, but
the variable will always refer to the same array.
Example 4.12.4-1. Final Variables
class Point {
int x, y;
int useCount;
Point(int x, int y) { this.x = x; this.y = y; }
static final Point origin = new Point(0, 0);
}
In this program, the class
Point
declares a
final
class variable
origin
. The
origin
variable
holds a reference to an object that is an instance of class
Point
whose coordinates are
(0, 0). The value of the variable
Point.origin
can never change, so it always refers to the
same
Point
object, the one created by its initializer. However, an operation on this
Point
object might change its state - for example, modifying its
useCount
or even, mislead-
ingly, its
x
or
y
coordinate.
A variable of primitive type or type
String
, that is
final
and initialized with a compile-time
Whether a variable is a constant variable or not may have implications with respect to
class initialization (§
12.4.1
)
, binary compatibility (§
13.1
,
§
13.4.9
)
and definite assignment
(§16).