Java Reference
In-Depth Information
hold a different value. All of the values, however, must be of the same data type.
The data type may be any valid data type including primitive, reference, or a
programmer-defined data type.
An index number , or subscript , is assigned to each element of the array,
allowing the program and the programmer to access individual values when
necessary. Index numbers are always integers. They begin with zero and progress
sequentially by whole numbers to the end of the array. The practice of zero-
indexing is common to many programming languages. It may help to think of the
first array element as being zero elements away from the beginning of the array.
Declaring and Constructing an Array
As with all variables, an array must be declared. The code to declare an array
first lists the data type, followed by a set of square brackets, followed by the
identifier name. For example, the code
int[] ages;
declares an array named ages with an integer data type. An alternate declaration,
similar to the C and C++ programming languages, places the square brackets
after the identifier.
int ages[];
Java uses brackets instead of parentheses for arrays so that the arrays are not
confused with methods.
In the above examples, an array named ages is declared that will hold integer
values. The actual array, however, is not constructed by either of these declara-
tions. You must construct the array and specify its length , or total number of
elements in the array, with an = new constructor statement.
ages = new int[100];
Often an array is declared and constructed in a single statement.
int[] ages = new int[100];
This declaration tells the Java compiler that ages will be used as the name of an
array containing integers and to construct a new array containing 100 elements.
Remember that Java uses zero-indexing, so the 100 constructed elements will be
numbered using indices 0 through 99.
An array is an object, and like any other object in Java, it is constructed as
the program is running and not at compile time. The array constructor uses
different syntax than most object constructors because it must initialize the
length of the array, which is established when the array is created at run time.
After creation, an array is a fixed-length structure. In other words, once an array
has been constructed, the number of elements it contains does not change. If
you need to refer to the length of the array in code, you can use the code
int size = arrayName.length
to refer to the length of the array as a property, and assign it to an integer.
Programmers used to other programming languages may be inclined to follow
the length property with an empty set of parentheses. In Java, however, length is
not a method; it is a property provided by the Java platform for all arrays.
Search WWH ::




Custom Search