<html>
<head>
<title> Arrays</title>
</head>
<body BGCOLOR=#eeeeff text=#000000 LINK=#0000ff VLINK=#000077 ALINK=#ff0000>
<table border="0" width="100%">
<tr>
<td><a href="jTOC.doc.html">Contents</a> | <a href="interfaces.doc.html">Prev</a> | <a href="exceptions.doc.html">Next</a> | <a href="jIX.fm.html">Index</a></td>
<td align=right><i>Java Language Specification</i><br>
<font size="-1">Second Edition</font></td></tr></table>
<hr><br>
<a name="27803"></a>
<p><strong>
CHAPTER
10 </strong></p>
<a name="27805"></a>
<h1>Arrays</h1>
<hr><p>
<a name="25550"></a>
In the Java programming language <em>arrays</em> are objects <a href="typesValues.doc.html#12028">(§4.3.1)</a>, are dynamically created, and may be assigned to variables of type <code>Object</code> <a href="typesValues.doc.html#11055">(§4.3.2)</a>. All methods of class <code>Object</code> may be invoked on an array.<p>
<a name="25500"></a>
An array object contains a number of variables. The number of variables may be zero, in which case the array is said to be <em>empty</em>. The variables contained in an array have no names; instead they are referenced by array access expressions that use nonnegative integer index values. These variables are called the <em>components</em> of the array. If an array has <em>n</em> components, we say <em>n</em> is the <em>length</em> of the array; the components of the array are referenced using integer indices from 0 to <i>n</i> - 1, inclusive.<p>
<a name="61129"></a>
All the components of an array have the same type, called the <em>component type</em> of the array. If the component type of an array is <i>T</i>, then the type of the array itself is written <i>T</i><code>[]</code>.<p>
<a name="61371"></a>
The value of an array component of type <code>float</code> is always an element of the float value set <a href="typesValues.doc.html#9208">(§4.2.3)</a>; similarly, the value of an array component of type <code>double</code> is always an element of the double value set. It is not permitted for the value of an array component of type <code>float</code> to be an element of the float-extended-exponent value set that is not also an element of the float value set, nor for the value of an array component of type <code>double</code> to be an element of the double-extended-exponent value set that is not also an element of the double value set.<p>
<a name="25502"></a>
The component type of an array may itself be an array type. The components of such an array may contain references to subarrays. If, starting from any array type, one considers its component type, and then (if that is also an array type) the component type of that type, and so on, eventually one must reach a component type that is not an array type; this is called the <em>element type</em> of the original array, and the components at this level of the data structure are called the <em>elements</em> of the original array.<p>
<a name="63008"></a>
There are some situations in which an element of an array can be an array: if the element type is <code>Object</code> or <code>Cloneable</code> or <code>java.io.Serializable</code>, then some or all of the elements may be arrays, because any array object can be assigned to any variable of these types.
<a name="25518"></a>
<h2>10.1 Array Types</h2>
<a name="25519"></a>
An array type is written as the name of an element type followed by some number of empty pairs of square brackets <code>[]</code>. The number of bracket pairs indicates the depth of array nesting. An array's length is not part of its type.<p>
<a name="30943"></a>
The element type of an array may be any type, whether primitive or reference. In particular:<p>
<ul><a name="26084"></a>
<li>Arrays with an interface type as the component type are allowed. The elements of such an array may have as their value a null reference or instances of any type that implements the interface.
<a name="26075"></a>
<li>Arrays with an <code>abstract</code> class type as the component type are allowed. The elements of such an array may have as their value a null reference or instances of any subclass of the <code>abstract</code> class that is not itself <code>abstract</code>.
</ul><a name="25523"></a>
Array types are used in declarations and in cast expressions <a href="expressions.doc.html#238146">(§15.16)</a>.<p>
<a name="25891"></a>
<h2>10.2 Array Variables</h2>
<a name="17235"></a>
A variable of array type holds a reference to an object. Declaring a variable of array type does not create an array object or allocate any space for array components. It creates only the variable itself, which can contain a reference to an array. However, the initializer part of a declarator <a href="classes.doc.html#40898">(§8.3)</a> may create an array, a reference to which then becomes the initial value of the variable.<p>
<a name="61598"></a>
Because an array's length is not part of its type, a single variable of array type may contain references to arrays of different lengths.<p>
<a name="25894"></a>
Here are examples of declarations of array variables that do not create arrays:
<blockquote><pre>
int[] ai; // array of int
short[][] as; // array of array of short
Object[] ao, // array of Object
otherAo; // array of Object
short s, // scalar short
aas[][]; // array of array of short
</pre></blockquote><a name="25902"></a>
Here are some examples of declarations of array variables that create array objects:<p>
<blockquote><pre>
Exception ae[] = new Exception[3];
Object aao[][] = new Exception[2][3];
int[] factorial = { 1, 1, 2, 6, 24, 120, 720, 5040 };
char ac[] = { 'n', 'o', 't', ' ', 'a', ' ',
'S', 't', 'r', 'i', 'n', 'g' };
String[] aas = { "array", "of", "String", };
</pre></blockquote><a name="25909"></a>
The <code>[]</code> may appear as part of the type at the beginning of the declaration, or as part of the declarator for a particular variable, or both, as in this example:<p>
<blockquote><pre>byte[] rowvector, colvector, matrix[];
</pre></blockquote><a name="25911"></a>
This declaration is equivalent to:<p>
<blockquote><pre>byte rowvector[], colvector[], matrix[][];
</pre></blockquote><a name="25915"></a>
Once an array object is created, its length never changes. To make an array variable refer to an array of different length, a reference to a different array must be assigned to the variable.<p>
<a name="25953"></a>
If an array variable <i>v</i> has type <i>A</i><code>[]</code>, where <i>A</i> is a reference type, then <i>v</i> can hold a reference to an instance of any array type <i>B</i><code>[]</code>, provided <i>B</i> can be assigned to <i>A</i>. This may result in a run-time exception on a later assignment; see <a href="arrays.doc.html#11430">§10.10</a> for a discussion.<p>
<a name="25959"></a>
<h2>10.3 Array Creation</h2>
<a name="25650"></a>
An array is created by an array creation expression <a href="expressions.doc.html#46168">(§15.10)</a> or an array initializer <a href="arrays.doc.html#11358">(§10.6)</a>.<p>
<a name="25675"></a>
An array creation expression specifies the element type, the number of levels of nested arrays, and the length of the array for at least one of the levels of nesting. The array's length is available as a final instance variable <code>length</code>.<p>
<a name="25676"></a>
An array initializer creates an array and provides initial values for all its components. <p>
<a name="25566"></a>
<h2>10.4 Array Access</h2>
<a name="53523"></a>
A component of an array is accessed by an array access expression <a href="expressions.doc.html#239587">(§15.13)</a> that consists of an expression whose value is an array reference followed by an indexing expression enclosed by <code>[</code> and <code>]</code>, as in <code>A[i]</code>. All arrays are <code>0</code>-origin. An array with length <i>n</i> can be indexed by the integers <code>0</code> to <i>n</i><code>-1</code>.<p>
<a name="25570"></a>
Arrays must be indexed by <code>int</code> values; <code>short</code>, <code>byte</code>, or <code>char</code> values may also be used as index values because they are subjected to unary numeric promotion <a href="conversions.doc.html#170952">(§5.6.1)</a> and become <code>int</code> values. An attempt to access an array component with a <code>long</code> index value results in a compile-time error.<p>
<a name="61612"></a>
All array accesses are checked at run time; an attempt to use an index that is less than zero or greater than or equal to the length of the array causes an <code>ArrayIndexOutOfBoundsException</code>  to be thrown.<p>
<a name="54000"></a>
<h2>10.5 Arrays: A Simple Example</h2>
<a name="25421"></a>
The example:<p>
<blockquote><pre>class Gauss {
public static void main(String[] args) {
int[] ia = new int[101];
for (int i = 0; i < ia.length; i++)
ia[i] = i;
int sum = 0;
for (int i = 0; i < ia.length; i++)
sum += ia[i];
System.out.println(sum);
}
}
</pre></blockquote><a name="25454"></a>
that produces the output:<p>
<blockquote><pre>5050
</pre></blockquote><a name="25463"></a>
declares a variable <code>ia</code> that has type array of <code>int</code>, that is, <code>int[]</code>. The variable <code>ia</code> is initialized to reference a newly created array object, created by an array creation expression <a href="expressions.doc.html#46168">(§15.10)</a>. The array creation expression specifies that the array should have <code>101</code> components. The length of the array is available using the field <code>length</code>, as shown.<p>
<a name="61617"></a>
The example program fills the array with the integers from <code>0</code> to <code>100</code>, sums these integers, and prints the result.
<a name="11358"></a>
<h2>10.6 Array Initializers</h2>
<a name="25749"></a>
An <em>array initializer</em> may be specified in a declaration, or as part of an array creation expression <a href="expressions.doc.html#46168">(§15.10)</a>, creating an array and providing some initial values:<p>
<ul><pre>
<em>ArrayInitializer:
<code>{ </code>VariableInitializers<sub><i>opt</i></sub><code> ,</code><sub><i>opt</i></sub><code> }
</code>
VariableInitializers:
VariableInitializer
VariableInitializers<code> , </code>VariableInitializer
</em></pre></ul><a name="25741"></a>
The following is repeated from <a href="classes.doc.html#40898">§8.3</a> to make the presentation here clearer:<p>
<ul><pre>
<em>VariableInitializer:
Expression
ArrayInitializer
</em></pre></ul><a name="25727"></a>
An array initializer is written as a comma-separated list of expressions, enclosed by braces "<code>{</code>" and "<code>}</code>".<p>
<a name="64369"></a>
The length of the constructed array will equal the number of expressions.<p>
<a name="25755"></a>
The expressions in an array initializer are executed from left to right in the textual order they occur in the source code. The <em>n</em>th variable initializer specifies the value of the <em>n-1</em>st array component. Each expression must be assignment-compatible <a href="conversions.doc.html#184206">(§5.2)</a> with the array's component type, or a compile-time error results.<p>
<a name="25756"></a>
If the component type is itself an array type, then the expression specifying a component may itself be an array initializer; that is, array initializers may be nested.<p>
<a name="61622"></a>
A trailing comma may appear after the last expression in an array initializer and is ignored.<p>
<a name="25758"></a>
As an example:
<blockquote><pre>class Test {
public static void main(String[] args) {
int ia[][] = { {1, 2}, null };
for (int i = 0; i < 2; i++)
for (int j = 0; j < 2; j++)
System.out.println(ia[i][j]);
}
}
</pre></blockquote><a name="25767"></a>
prints:<p>
<blockquote><pre>1
2
</pre></blockquote><a name="61627"></a>
before causing a <code>NullPointerException</code> in trying to index the second component of the array <code>ia</code>, which is a null reference.<p>
<a name="64347"></a>
<h2>10.7 Array Members</h2>
<a name="64511"></a>
The members of an array type are all of the following:<p>
<ul><a name="64513"></a>
<li>The <code>public</code> <code>final</code> field <code>length</code>, which contains the number of components of the array (<code>length</code> may be positive or zero)
<a name="64515"></a>
<li>The <code>public</code> method <code>clone</code>, which overrides the method of the same name in class <code>Object</code> and throws no checked exceptions
<a name="64517"></a>
<li>All the members inherited from class <code>Object</code>; the only method of <code>Object</code> that is not inherited is its <code>clone</code> method
</ul><a name="29781"></a>
<p>
<a name="62964"></a>
An array thus has the same public fields and methods as the following class:<p>
<blockquote><pre>class A implements Cloneable, java.io.Serializable {
public final int length = <sup>X</sup>;
public Object clone() {
try {
return super.clone();
} catch (CloneNotSupportedException e) {
throw new InternalError(e.getMessage());
}
}
}
</pre></blockquote><a name="61637"></a>
Every array implements the interfaces <code>Cloneable</code> and <code>java.io.Serializable</code>. <p>
<a name="61641"></a>
That arrays are cloneable is shown by the test program:
<blockquote><pre>class Test {
public static void main(String[] args) {
int ia1[] = { 1, 2 };
int ia2[] = (int[])ia1.clone();
System.out.print((ia1 == ia2) + " ");
ia1[1]++;
System.out.println(ia2[1]);
}
}
</pre></blockquote><a name="25812"></a>
which prints:<p>
<blockquote><pre>false 2
</pre></blockquote><a name="61648"></a>
showing that the components of the arrays referenced by <code>ia1</code> and <code>ia2</code> are different variables. (In some early implementations of the Java programming language this example failed to compile because the compiler incorrectly believed that the clone method for an array could throw a <code>CloneNotSupportedException</code>.)<p>
<a name="61654"></a>
A <code>clone</code> of a multidimensional array is shallow, which is to say that it creates only a single new array. Subarrays are shared.<p>
<a name="61652"></a>
This is shown by the example program:
<blockquote><pre>class Test {
public static void main(String[] args) throws Throwable {
int ia[][] = { { 1 , 2}, null };
int ja[][] = (int[][])ia.clone();
System.out.print((ia == ja) + " ");
System.out.println(ia[0] == ja[0] && ia[1] == ja[1]);
}
}
</pre></blockquote><a name="25855"></a>
which prints:<p>
<blockquote><pre>false true
</pre></blockquote><a name="61659"></a>
showing that the <code>int[]</code> array that is <code>ia[0]</code> and the <code>int[]</code> array that is <code>ja[0]</code> are the same array.<p>
<a name="40879"></a>
<h2>10.8 <code></code>Class<code></code> Objects for Arrays</h2>
<a name="40882"></a>
Every array has an associated <code>Class</code> object, shared with all other arrays with the same component type. The direct superclass of an array type is <code>Object</code>. Every array type implements the interfaces <code>Cloneable</code> and <code>java.io.Serializable</code>.<p>
<a name="62923"></a>
This is shown by the following example code:
<blockquote><pre>class Test {
public static void main(String[] args) {
int[] ia = new int[3];
System.out.println(ia.getClass());
System.out.println(ia.getClass().getSuperclass());
}
}
</pre></blockquote><a name="40893"></a>
which prints:<p>
<blockquote><pre>class [I
class java.lang.Object
</pre></blockquote><a name="40896"></a>
where the string "<code>[I</code>" is the run-time type signature for the class object "array with component type <code>int</code>".<p>
<a name="25726"></a>
<h2>10.9 An Array of Characters is Not a String</h2>
<a name="25730"></a>
In Java programming language, unlike C, an array of <code>char</code> is not a <code>String</code>, and neither a <code>String</code> nor an array of <code>char</code> is terminated by <code>'\u0000'</code> (the NUL character).<p>
<a name="25731"></a>
A <code>String</code> object is immutable, that is, its contents never change, while an array of <code>char</code> has mutable elements. The method <code>toCharArray</code> in class <code>String</code> returns an array of characters containing the same character sequence as a <code>String</code>. The class <code>StringBuffer</code> implements useful methods on mutable arrays of characters.<p>
<a name="11430"></a>
<h2>10.10 Array Store Exception</h2>
<a name="61664"></a>
If an array variable <i>v</i> has type <i>A</i><code>[]</code>, where <i>A</i> is a reference type, then <i>v</i> can hold a reference to an instance of any array type <i>B</i><code>[]</code>, provided <i>B</i> can be assigned to <i>A</i>.<p>
<a name="53134"></a>
Thus, the example:
<blockquote><pre>class Point { int x, y; }
class ColoredPoint extends Point { int color; }
class Test {
public static void main(String[] args) {
ColoredPoint[] cpa = new ColoredPoint[10];
Point[] pa = cpa;
System.out.println(pa[1] == null);
try {
pa[0] = new Point();
} catch (ArrayStoreException e) {
System.out.println(e);
}
}
}
</pre></blockquote><a name="25743"></a>
produces the output:<p>
<blockquote><pre>true
java.lang.ArrayStoreException
</pre></blockquote><a name="26018"></a>
Here the variable <code>pa</code> has type <code>Point[]</code> and the variable <code>cpa</code> has as its value a reference to an object of type <code>ColoredPoint[]</code>. A <code>ColoredPoint</code> can be assigned to a <code>Point</code>; therefore, the value of <code>cpa</code> can be assigned to <code>pa</code>.<p>
<a name="26025"></a>
A reference to this array <code>pa</code>, for example, testing whether <code>pa[1]</code> is <code>null</code>, will not result in a run-time type error. This is because the element of the array of type <code>ColoredPoint[]</code> is a <code>ColoredPoint</code>, and every <code>ColoredPoint</code> can stand in for a <code>Point</code>, since <code>Point</code> is the superclass of <code>ColoredPoint</code>.
<p>
<a name="61669"></a>
On the other hand, an assignment to the array <code>pa</code> can result in a run-time error. At compile time, an assignment to an element of <code>pa</code> is checked to make sure that the value assigned is a <code>Point</code>. But since <code>pa</code> holds a reference to an array of <code>ColoredPoint</code>,  the assignment is valid only if the type of the value assigned at run-time is, more specifically, a <code>ColoredPoint</code>.
<a name="26044"></a>
<p>
The Java virtual machine checks for such a situation at run-time to ensure that the assignment is valid; if not, an <code>ArrayStoreException</code> is thrown. More formally: an assignment to an element of an array whose type is <i>A</i><code>[]</code>, where <i>A</i> is a reference type, is checked at run-time to ensure that the value assigned can be assigned to the actual element type of the array, where the actual element type may be any reference type that is assignable to <i>A</i>.
<a name="26055"></a>
<p>
<hr>
<table border="0" width="100%">
<tr>
<td><a href="jTOC.doc.html">Contents</a> | <a href="interfaces.doc.html">Prev</a> | <a href="exceptions.doc.html">Next</a> | <a href="jIX.fm.html">Index</a></td>
<td align=right><i>Java Language Specification</i><br>
<font size="-1">Second Edition</font></td></tr></table>
<i><a href="jcopyright.doc.html">Copyright</a> © 2000 Sun Microsystems, Inc.
All rights reserved</i>
<br>
Please send any comments or corrections to <a href="mailto:
[email protected]">
[email protected]</a>
</font>
</body></html>