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 {
} |
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.
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. |