Just as you can pass primitive type values to methods, you can also pass arrays to a method. To pass an array to a method, specify the name of the array without any square brackets within the method call. Unlike C/C++, in Java every array object knows its own length using its length field, therefore while passing array’s object reference into a method, we do not need to pass the array length as an additional argument. For example: Suppose we have an integer array num containing 10 elements.
int[] num = new int[10];
Then the method call will look like, modify (num);
As array reference is passed to the method so the corresponding parameter in the called method header must be of array type. The method body in our example will be
modify (int [] x) {…………………………}
It indicates that the method modify receives the reference of an integer array (in our case num) in parameter x when it is being called. So if parameter x is being used in its body then actually it is referencing an array object num in the calling method.
Recall that when you pass a variable of primitive type as an argument to a method, the method actually gets a copy of value stored in the variable. So when an individual array element of primitive type is passed, the matching parameter receives a copy. However, when an array is passed as an argument, you just pass the array’s reference in matching parameter and not the copy of individual elements. Any modification made in the array using its reference will be visible to the caller.
class sortNumbers
{
public static void main(String[] args)
{
int[] data={40,50,10,30,20,5};
System.out.println("Unsorted List is :");
display(data);
sort(data);
System.out.println("\nSorted List is :");
display(data);
}
static void display(int num[])
{
for(int i=0; i<num.length;i++)
System.out.print(num[i] + " ");
}
static void sort(int num[])
{
int i, j, temp;
for(i=0; i<num.length-i;i++)
{
for(j=0; j<num.length-i-1;j++)
{
if(num[j]>num[j+1])
{
temp = num[j];
num[j] = num[j+1];
num[j+1] = temp;
}
}
}
}
}
In this example, we sort the numbers by using the concept of passing arrays to methods. The unsorted array is passed to the sort () method. In the method’s definition, the array referenced using num reference variable is sorted and the changes made are reflected back.