Parameters
Up until this point, we have glossed over exactly what happens when we pass parameters to methods. Suppose our full program looked like this:
import java.util;
public class TestParams
{
public static void main(String[] args)
{
int val = 4;
TestParams.addOne(val);
System.out.println(val);
int[] array = {1, 2, 3};
TestParams.zeroArray(array);
for (int x : array)
{
System.out.println(x);
}
}
public static void addOne(int num)
{
num++;
}
public static void zeroArray(int[] arr)
{
for (int i = 0; i < arr.length; i++)
{
arr[i] = 0;
}
}
}It turns out that when we pass parameters that are ints, doubles, chars, or bools, then they are passed by value. This means that when we do something like:
TestParams.addOne(val);Then the VALUE of val is passed – not val itself. This means that the value 4 is passed, and
so the num parameter in the addOne method gets set to 4. We then add one to the num
parameter, so that it has the value 5. When we finish executing this method, we return back to
the main method after the call to addOne. At this point, we print out the value of val. This
print statement will print out 4. Even though we added one to num in addOne, num IS NOT
val – it was just initialized to have the same value that val did.
On the other hand, arrays (and later objects) are passed by reference. This means that when we do something like this:
TestParams.zeroArray(array);Then what we are really passing is the address of array in memory. Then, the arr parameter
will be initialized to reference the same array in memory. When we set every element in arr
(which is the SAME array as array) to zero, then it does change the original array. So when
we print out array in main after the call to zeroArray, it will print out all 0’s for the
elements (because every element is set to zero in the zeroArray method).