Java Reference
In-Depth Information
However, we don't need to keep the sub-array lengths the same. This also works:
str[0] = new String[2];
str[1] = new String[33];
str[2] = new String[444];
We can combine the string array declaration and initialization, as in
str[0] = new String[] { " alice " , " bob " } ;
str[1] = new String[] { " cathy " , " don " , " ed " } ;
str[2] = new String[] { " fay " , " grant " , " hedwig " , " ward " } ;
System.out.println ("str[1][2],str[2][3] ="+
str[1][2] + str[2][3]);
The print statement would show
str[1][1],str[2][3] = edward
4.7.4 More about arrays as objects
As mentioned earlier, arrays in Java are objects. An array inherits Object and
possesses an accessible property - length - that gives the number of elements
in the array. For example, if a method uses Object as a parameter, as in
void aMethod (Object obj) {...}
then an array can be passed as the actual parameter since an array is a subclass
of Object :
...
int[] i - array = new int[10];
aMethod (i - array);
...
To make arrays appear in a convenient and familiar form (as in C, for example),
the language designers provided brackets as the means of accessing the array
elements as already seen above. Without brackets, an array class would have to
provide a method such as getElementAtIndex() to access array elements.
Forexample,
String string - one = str - array.getElementAtIndex (1);
Fortunately, the simpler syntax using brackets was chosen instead:
String string - one = strArray[1];
Since arrays are objects, arrays are somewhat more complicated in Java than
in other languages, but the class structure also provides important benefits. For
example, each use of an array element results in a check on the element number,
Search WWH ::




Custom Search