MathBits.com
Return to Unit Menu | Java Main Page | MathBits.com | Terms of Use  

 

Passing Arrays to Methods
(resembles "pass-by-reference")

When discussing arguments/parameters and methods, we talked about passing-by-valueCopies of argument values are sent to the method, where the copy is manipulated and in certain cases, one value may be returned.  While the copied values may change in the method, the original values in main did not change (unless purposely reassigned after the method).
 
The situation, when working with arrays, is somewhat different.  If we were to make copies of arrays to be sent to methods, we could potentially be copying very large amounts of data.
Not very efficient!

Passing an array mimics a concept called "pass-by-reference", meaning that when an array is passed as an argument, its memory address location (its "reference") is used.  In this way, the contents of an array CAN be changed inside of a method, since we are dealing directly with the actual array and not with a copy of the array.
Note: In Java, a pointer value to the memory address location is used, making arrays "pass-by-value" (and not actually "pass-by-reference" as seen in C++.)

int [ ] num = {1, 2, 3};
testingArray(num);   //Method call
System.out.println("num[0] = " + num[0] + "\n num[1] = " + num[1] + "\n num[2] =" + num[2]);
. . . 

//Method for testing
public static void testingArray(int[ ] value)
{
    value[0] = 4;
    value[1] = 5;
    value[2] = 6;
}
Output:
num[0] = 4
num[1] = 5
num[2] = 6
(The values in the array have been changed.
Notice that nothing was "returned".)
You will need to be careful when sending an array to a method.  Remember that any changes made to the array in the method will change the data in the original array.  Be sure that your intention is to change the original data (thus losing the original data). 
 

Example:  Fill an array with 10 integer values.  Pass the array to a method that will add up the values and return the sum.  (In this example, no original data in the array was altered.  The array information was simply used to find the sum.)

import java.io.*;
import BreezyGUI.*;

public class FindSum
{
     public static void main (String [ ] args)
     {
            int [ ]  number = new int [ 10];  
// instantiate the array
           
int i;
            int sum=0;

            for ( i = 0; i < 10; i++ )            // fill the array
               number[ i ] = Console.readInt("Enter number: " );

            int sum = find_sum(number);   // invoke the method
     
    
 System.out.println("The sum is" +sum + ".");
     }

    public static int  find_sum(int [ ] value)  //method definition to find sum
    {
          int i, total = 0;
          for(i=0; i<10; i++)
          {
              total = total + value[ i ];
          }

          return (total);
     }

 

 


Return to Unit Menu | Java Main Page | MathBits.com | Terms of Use