Java Reference
In-Depth Information
A program can create several arrays in a single declaration. The following declaration
reserves 100 elements for b and 27 elements for x :
String[] b = new String[ 100 ], x = new String[ 27 ];
When the type of the array and the square brackets are combined at the beginning of the
declaration, all the identifiers in the declaration are array variables. In this case, variables b
and x refer to String arrays. For readability, we prefer to declare only one variable per dec-
laration. The preceding declaration is equivalent to:
String[] b = new String[ 100 ]; // create array b
String[] x = new String[ 27 ]; // create array x
Good Programming Practice 7.1
For readability, declare only one variable per declaration. Keep each declaration on a sep-
arate line, and include a comment describing the variable being declared.
When only one variable is declared in each declaration, the square brackets can be
placed either after the type or after the array variable name, as in:
String b[] = new String[ 100 ]; // create array b
String x[] = new String[ 27 ]; // create array x
but placing the square brackets after the type is preferred.
Common Programming Error 7.3
Declaring multiple array variables in a single declaration can lead to subtle errors. Consider
the declaration int[] a, b, c; . If a , b and c should be declared as array variables, then this
declaration is correct—placing square brackets directly following the type indicates that all
the identifiers in the declaration are array variables. However, if only a is intended to be an
array variable, and b and c are intended to be individual int variables, then this declara-
tion is incorrect—the declaration int a[], b, c; would achieve the desired result.
A program can declare arrays of any type. Every element of a primitive-type array con-
tains a value of the array's declared element type. Similarly, in an array of a reference type,
every element is a reference to an object of the array's declared element type. For example,
every element of an int array is an int value, and every element of a String array is a ref-
erence to a String object.
7.4 Examples Using Arrays
This section presents several examples that demonstrate declaring arrays, creating arrays,
initializing arrays and manipulating array elements.
7.4.1 Creating and Initializing an Array
The application of Fig. 7.2 uses keyword new to create an array of 10 int elements, which
are initially zero (the default initial value for int variables). Line 9 declares array —a ref-
erence capable of referring to an array of int elements—then initializes the variable with
a reference to an array object containing 10 int elements. Line 11 outputs the column
headings. The first column contains the index (0-9) of each array element, and the second
column contains the default initial value (0) of each array element.
 
 
 
Search WWH ::




Custom Search