Passing Arrays and Elements to Methods

 

Introduction.  Remember when we passed arguments into methods a copy of each value was placed into a local variable within the method.  The declaration of the method also declares the variables within its parentheses.  This approach is called passing by value.

In C++, the developer has more options as to whether they want things passed into methods/functions to be operated on themselves or whether they want a new variable local to the method/function to be created and used.  One way to get the original variable to be operated on within the method is to pass by reference so that the memory location of the variable is passed and the method/function will access whatever is at that memory location and operate on it.

In Java, by default arguments are pass by value, so that unless variables are defined globally and referred to be the same name in methods they will not be changed.

But, for reasons unknown to me, this is not the case when passing entire arrays.  Passing the entire array by passing the name of an array as a whole causes it to be passed by reference.  This causes the method to go to the actual location in memory and operate on the original array.  On the other hand, the default for individual elements of the array stays as pass by value so that individual elements will not be modified.

While this program is relatively artificial in its application it does demonstrate some fundamental syntax.   You should call this Java applet PassArray.java.

 

import java.awt.Container;
import javax.swing.*;

public class PassArray extends JApplet
{

JTextArea outputArea;
String output;

public void init( )
{

outputArea = new JTextArea();
Container c = getContentPane();
c.add(outputArea);

int a[] = {1,2,3,4,5};

output = "By default arrays are passed-by-reference,\n" +
"so that memory location of the array is passed:\n" +
"This implies the actual array elements are worked on\n\n" +
"The values of the original array are:\n";

for (int i = 0; i < a.length; i++)
output = output + " " + a[i];

// the array is passed-by-reference
// so array itself is used in the method

modifyArray(a);

output = output + "\n\nThe values of the passed array are:\n";

for (int i = 0; i < a.length; i++)

output = output + " " + a[i];

output = output + "\n\nArray elements are " +
"pass-by-value:\n" +
"a[3] before modifyElement: "+ a[3];

//  here we pass only an element
//  so we are passing by value
//  to a variable local to the method

modifyElement(a[3]);

output = output + "\na[3] after modifyElement: " + a[3];

outputArea.setText(output);

}

public void modifyArray(int b[])
{

for (int j = 0; j < b.length; j++)

b[j] = 2*b[j];

}

public void modifyElement( int e )
{

e = 2*e;

}

}

 

The following listing is for PassArray.html.  We present it mainly to make sure you get a reasonable display on your first attempt.

 

<html>
<applet code="PassArray.class" width=300 height=300>
</applet>
</html>

 

Before we discuss this you should run it and get the output in the following self-explanatory image.

 

 

Code Discussion.  We will use our usual outline form to discuss the code.

  • import java.awt.Container
  • import javax.swing for output
  • declare the overall inclusive class PassArray to extend JApplet
  • declare method init( )
    • declare and initialize a JTextArea called outputArea
    • declare and initialize a Container called c to be the content pane of the applet
    • add outputArea to the container
    • declare and initialize an array of integers with a list
      • the array is called a
      • square brackets are used to indicate it is an array
    • declare and initialize a String called output giving some description of the program motivation
    • a loop is used to go through the array
      • notice it starts at 0
      • notice its upper limit is indicated by  < a.length  so that in order to go through the entire array
      • each element in the array is added to the output string two spaces over from the previous one
    • the array is passed to a method called modifyArray( ) by passing the name of the array with no indication of its size
    • a header for displaying the results of this method is appended to the output string
    • a loop is used to go through the array
      • each element in the array is added to the output string two spaces over from the previous one
    • a header for displaying the results of the next section of code is appended to the output string
    • now the fourth entry in the array, a[3] is displayed
    • now the fourth entry in the array, a[3], is passed to a method called modifyElement( ) by passing a[3]
    • now the fourth entry in the array, a[3] has been passed it is displayed
    • the outputArea has its contents set to the string output

 

  • method modifyArray( ) is declared and developed
  • nothing is returned so it is public void modifyArray(int b[ ])
    • it obtains a pass by reference to an entire array
      • the array is actually called b in the method but since it is located at the same place as a, the a will actually be operated on
    • a for loop is used to go through the entire array
      • each element in the array is doubled

 

  • method modifyElement( ) is declared and developed
  • nothing is returned so it is public void modifyElement(int e)
    • it obtains a pass by value for this individual argument
      • the argument is copied into a local variable e
      • this local variable is doubles

 

Thus the output demonstrates how the elements of the array are changed when passed to a method, but the individual element isn't actually changed when it is passed to a method.

Our next webpage will use a GUI to get test scores from the user, place them into an array, compute their average and display the results to the GUI.