Java Reference
In-Depth Information
An array is a special kind of object that holds zero or more primitive values or refer‐
ences. These values are held in the elements of the array, which are unnamed vari‐
ables referred to by their position or index . The type of an array is characterized by
its element type , and all elements of the array must be of that type.
Array elements are numbered starting with zero, and valid indexes range from zero
to the number of elements minus one. The array element with index 1, for example,
is the second element in the array. The number of elements in an array is its length .
The length of an array is specified when the array is created, and it never changes.
a x
The element type of an array may be any valid Java type, including array types. This
means that Java supports arrays of arrays, which provide a kind of multidimensional
array capability. Java does not support the matrix-style multidimensional arrays
found in some languages.
Array Types
Array types are reference types, just as classes are. Instances of arrays are objects,
just as the instances of a class are. 4 Unlike classes, array types do not have to be
defined. Simply place square brackets after the element type. For example, the fol‐
lowing code declares three variables of array type:
byte b ; // byte is a primitive type
byte [] arrayOfBytes ; // byte[] is an array of byte values
byte [][] arrayOfArrayOfBytes ; // byte[][] is an array of byte[]
String [] points ; // String[] is an array of strings
The length of an array is not part of the array type. It is not possible, for example, to
declare a method that expects an array of exactly four int values, for example. If a
method parameter is of type int[] , a caller can pass an array with any number
(including zero) of elements.
Array types are not classes, but array instances are objects. This means that arrays
inherit the methods of java.lang.Object . Arrays implement the Cloneable inter‐
face and override the clone() method to guarantee that an array can always be
cloned and that clone() never throws a CloneNotSupportedException . Arrays also
implement Serializable so that any array can be serialized if its element type can
be serialized. Finally, all arrays have a public final int field named length that
specifies the number of elements in the array.
Array type widening conversions
Because arrays extend Object and implement the Cloneable and Serializable
interfaces, any array type can be widened to any of these three types. But certain
4 There is a terminology difficulty when discussing arrays. Unlike with classes and their instances,
we use the term “array” for both the array type and the array instance. In practice, it is usually
clear from context whether a type or a value is being discussed.
Search WWH ::

Custom Search