THE Java™ Programming Language, Fourth Edition

(Jeff_L) #1

final String name;


NamedObj(String name) {
this.name = name;
}
}


or when you must calculate the value in something more sophisticated than an initializer expression:


static final int[] numbers = numberList();
static final int maxNumber; // max value in numbers


static {
int max = numbers[0];
for (int num : numbers) {
if (num > max)
max = num;
}
maxNumber = max;
}


static int[] numberList() {
// ...
}


The compiler will verify that all static final fields are initialized by the end of any static initializer blocks, and
that non-static final fields are initialized by the end of all construction paths for an object. A compile-time
error will occur if the compiler cannot determine that this happens.


Blank final local variables are useful when the value to be assigned to the variable is conditional on the value
of other variables. As with all local variables, the compiler will ensure that a final local variable is initialized
before it is used.


Local variables and parameters are usually declared final only when they will be accessed by a local, or
anonymous inner, classthough some people advocate always making parameters final, both as a matter of
style, and to avoid accidentally assigning a value to a parameter, when a field or other variable was intended.
Issues regarding when you should, and should not, use final on fields were discussed on page 46.


7.4. Array Variables


Arrays provide ordered collections of elements. Components of an array can be primitive types or references
to objects, including references to other arrays. Arrays themselves are objects and extend Object. The
declaration


int[] ia = new int[3];


declares an array named ia that initially refers to an array of three int values.


Array dimensions are omitted in the type declaration of an array variable. The number of components in an
array is determined when it is created using new, not when an array variable is declared. An array object's
length is fixed at its creation and cannot be changed. Note that it is the length of the array object that is fixed.

Free download pdf