Arrays as Method Arguments and Return Types


Since arrays are so widely used in scientific and engineering programs, there will be times when you want to define an array as an input parameter to a method, pass an array as an argument to a method, or define an array as the return type for a method. Fortunately, all of these things are possible. To define an array as an input parameter, simply include the array type, an array name , and the appropriate number of bracket pairs in the input argument list. For example, a method named blah() that declares a 1-D array of double values named data[] as an input parameter might have a declaration statement like

 public void blah(double data[]) 

To pass an array as an argument to a method, simply type the array name by itself without any square brackets. For example, to pass a 1-D array named pressure[] to the blah() method, you might type

 blah(pressure); 

Arrays are objects, so a reference to the array is passed to the method. Any changes made to the array elements in the method will persist when the method exits. Once inside the method, the number of elements of each dimension of the array can be determined using the length property described later in this chapter.

A method can define an array to be its return type by using the array element type and the appropriate number of brackets. For example, a public method named getArray() that returns a 2-D integer array might have the following signature ”

 public int[][] getArray() 

Example: Passing an Array as a Method Argument

The printArray() method is a static method that prints the elements of a 2-D array. The array is passed to the method by providing the array name as an argument. Inside the printArray() method, the number of rows and columns of the array to be printed is obtained using the length field described in the next section.

 public class ArgDemo {   public static void main(String args[]) {     double data[][] = { {1.2, 2.3, 3.4, 4.5},                         {0.1, 7.8, 11.2, 0.1} };     //  The printArray() method is called sending the     //  data[][] array as an argument.     printArray(data);   }   //  This method prints the elements of a 2-D array   //  array.length gives the number of rows   //  array[j].length gives the number of columns   //  in a given row.   public static void printArray(double array[][]) {     for(int i=0; i<array.length; ++i) {       for(int j=0; j<array[i].length; ++j) {         System.out.println("[" + i + "][" + j + "] = " +                            array[i][j]);       }     }   } } 

Output ”

 [0][0] = 1.2 [0][1] = 2.3 [0][2] = 3.4 [0][3] = 4.5 [1][0] = 0.1 [1][1] = 7.8 [1][2] = 11.2 [1][3] = 0.1 


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