Array Length


Every array has a static field named length implicitly associated with it. For a 1-D array, the value of the length field is equal to the number of elements in the array. For multidimensional arrays, the value of length is equal to the number of nested subarrays. For example, the length field for a 2-D array will have a value equal to the number of nested 1-D arrays (i.e., rows) in the 2-D array. The length field is useful for cycling through the elements of an array or to determine the size of an array that was passed to a method.

To access the length property, type the array name , a period, and then length . For instance, to define a 1-D, five-element integer array ”

 int array[] = new int[5]; 

The value of array.length would be five, the number of elements in the array. Now let's consider the following 2-D array ”

 double data[][] = new double[2][3]; 

The syntax data.length would return the number 2, the number of rows in the array. The syntax data[0].length would return the number 3, the number of columns in the zeroth row of the array.

Example: Using length

To see the length field in action look at the "Passing an Array as a Method Argument" example in this chapter where the length field was used to determine the number of rows and columns in a 2-D array.



Technical Java. Applications for Science and Engineering
Technical Java: Applications for Science and Engineering
ISBN: 0131018159
EAN: 2147483647
Year: 2003
Pages: 281
Authors: Grant Palmer

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net