Passing Arrays to Methods in Java

Passing arrays to methods in Java | Just like we can pass primitive type values and objects to methods,

it is also possible to pass arrays and individual array elements as arguments to methods and returns arrays from methods.

When we pass an array argument to a method in java, actually, the reference of the array is passed to the method, not value.

Once an array is passed as an argument to a method, all elements of the array can be accessed by statements of the method.

In this tutorial, we will learn how to pass one-dimensional and multidimensional arrays as arguments to methods in java with example programs. So, let’s understand them one by one.

Passing One-dimensional Array as Arguments to Method in Java


A method that will take an array reference through a method call, method’s parameter list must define an array parameter. The general syntax to declare a method with parameter list one dimensional array is as follows:

data-type method-name(data-type array_name[ ])
{
   // statements
}
For example:
void display(int num[ ]) 
{
  // statements
}

Here, the presence of a pair of square brackets after the array name indicates that we are passing an array.

After a method is defined, while calling it, we need to pass the array name of actual array as an argument to a method.  To pass an array as an argument to a method, specify the name of array without any brackets.

The general syntax to call a method with passing an array reference is as follows:

method-name(array_name);

For example, if array num is declared as:

int[ ] num = new int[4];

then the method m1() call

m1(num);

Here, we are passing the reference of the array num to a method m1(). When we pass the reference of an array object into a method, we do not need to pass array length as an additional argument.


We can also pass an anonymous array as an argument to a method while calling the method. The general syntax to calling a method with passing an anonymous array as an argument is as follows:

method-name(new data-type[ ]{value0, value1, ..., valuek});
For example:
m1(new int[ ]{3, 1, 2, 6, 4, 2}); // Here, m1 is method name.

Let’s take a simple example program where we will display elements of one dimensional array.

Program source code 1:

package arraysProgram;
public class OneDArray 
{
  void show(int x[ ]) {
	 for(int i = 0; i < x.length; i++) 
	 {
	   System.out.print(x[i]+ " ");	 
	 }
  }
}
public class OneDArraytoMethod {
public static void main(String[ ] args) 
{
// Declare an array x with initialization.	
    int[ ] x = {2, 3, 4, 5, 6, 7, 8};

// Create an object of class OneDArray.
     OneDArray obj = new OneDArray();
     System.out.println("Value of array x: ");
      obj.show(x); // Calling show() method with passing 1D array.
  }
}
Output:
         Value of array x: 
         2 3 4 5 6 7 8 

In this program, we have defined a class OneDArray with a method named show(). The method show() accepts a one-dimensional array as an argument and does not return any value. The purpose of show() method is to print elements of one dimensional array passed to it.

In the main method, one dimensional array x is defined with the initialization of elements. obj.show(x); calls show() method with passing 1D array x and display elements of array on the console.

Arrays are passed by reference in Java, not pass by value


We know that Java uses pass-by-value (also called call-by-value) to pass arguments to a method. But there is an important difference between passing the values of variables of primitive data types and passing arrays. They are:

1. When an argument of any primitive type (boolean, char, byte, short, int, long, float, or double) is passed to a method, the argument’s value is passed. It means that if we make a change to a value passed to a method, the original value is not affected.

For more details, go to this tutorial: Call by value and Call by reference in Java

2. In Java, Arrays are objects. An object actually holds a memory address where the values are stored. When an argument of an array type is passed to a method, the value of an argument is actually the reference to an array that contains a copy of the memory address where values are stored.

Therefore, we can say that entire arrays are passed by reference, not value. It simply means that if we make a change to an array passed to a method, the original array is also affected.

Let’s understand this concept with the help of a simple example program. Concentrate on the source code to understand better.

Program source code 2:

package arraysProgram;
public class PassingArrays {
public static void main(String[] args) 
{
  int x = 2; // Original value.
  int[ ] num = {0, 1}; // Original array.
   m1(x, num);
   System.out.println("Value of x: " +x);
   System.out.println("Value of num[1]: " +num[1]);
 }
public static void m1(int x, int[ ] num) 
{
   x = 5; // Modifying value of x.
   num[1] = 20; // Modifying array. 
 }
}
Output:
      Value of x: 2
      Value of num[1]: 20

As you can observe in the output, the value of x is the same but the values of the array are changed when modified inside the method.

Thus, if we change the array in the method, we will also see the change outside the method. Look at the figure below to understand more.

Passing arrays to methods in Java


Note:

a) In Java, arrays are objects. JVM stores objects in the heap memory, which is used for dynamic memory allocation. In simple words, arrays are stored in the heap memory.

b) In some Java books, there is also written that an array is not passed by reference, but a reference to an array is passed by value.

c) When an individual array element as an argument is passed to a method, the called method gets a copy of element’s value.

It means that Java uses pass by value to pass an individual array element as an argument to a method. So, if we make a change to the value of individual array element passed to a method, the original array element is not affected.

Let’s take an example program based on this concept. Concentrate on the below source code to understand better.

Program source code 3:

package arraysProgram;
public class PassingArrays {
public static void main(String[] args) 
{
 int[ ] num = {2, 4}; // Original array.
 m1(num[0], num[1]); // Here, passing individual array elements (by pass by value mechanism).
 System.out.println("Value of num[0]: " +num[0]);
 System.out.println("Value of num[1]: " +num[1]);
 }
public static void m1(int x, int y) 
{
// Modifying values of array elements.
     x = 5;
     y = 20;
 }
}
Output:
          Value of num[0]: 2
          Value of num[1]: 4

4. Let’s create a program where we will demonstrate the difference between passing an entire array and passing array element of primitive data type to a method.

Program source code 4:

package arraysProgram;
public class PassingArrays {
public static void modifyArray(int[ ] num)
{
  for(int i = 0; i < num.length; i++)
   num[i] *= 2;	  
}
public static void modifyingArrayElement(int arrayElement)
{
   arrayElement *= 5;
   System.out.println("\nValue of arrayElement after modifying: " +arrayElement);
}
public static void main(String[] args) 
{
   int[ ] num = {10, 20, 30, 40, 50};
   System.out.println("Effect of passing reference to entire array:");
   System.out.println("Original array: ");

// Displaying elements of original array. 
    for(int values : num)
        System.out.printf(" %d", values);	
 
     modifyArray(num); // Passing array reference.
     System.out.println("\nModified array: ");
// Displaying modified array elements.  
    for(int values : num)
    {
  	 System.out.printf(" %d", values);
     }
  System.out.println("\n\nEffect of passing an element of array:");
  System.out.printf("num[3] before modifying: " +num[3]);
  modifyingArrayElement(num[3]); // Attempt to modify num[3].  
  System.out.println("num[3] after modifying: " +num[3]);
 }
}
Output:
          Effect of passing reference to entire array:
          Original array: 
            10 20 30 40 50
          Modified array: 
            20 40 60 80 100

          Effect of passing an element of array:
          num[3] before modifying: 80
          Value of arrayElement after modifying: 400
          num[3] after modifying: 80

Remember that when an individual primitive type array element is passed to a method, modifying the value of array element inside the called method does not affect the original value of that element in the calling method’s array.

Passing Two-dimensional Arrays to Methods in Java


For a method to take a two dimensional array as its argument, we must specify two dimensional array name followed by two pairs of square brackets preceded by the data type of array.

The general syntax of method definition is as follows:

data-type method-name(data-type array[ ][ ])
{
   // local variables
   // statements
}
For example:
void show(int x[ ][ ])
{
    // local variables
   // statements
}

While calling a method with two-dimensional array parameter list, just pass array name to the method like this:

object-reference.show(x);

Here, object-reference is a reference to an object of underlying class and x is a two-dimensional array declared in the program.


5. Let’s take an example program where we will display elements of a matrix.

Program source code 5:

package arraysProgram;
public class TwoDArray 
{
 void show(int x[ ][ ])
 {
    int i, j;
    System.out.println("Matrix x: ");
   for(i = 0; i < x.length; i++)
   {
	 for(j = 0; j < x.length; j++)
	   System.out.print(x[i][j]+ " ");
	   System.out.println();
   }
  }
}
public class PassingTwoDArrayToMethod {
public static void main(String[] args) 
{
 int x[ ][ ] = {{1, 2},{3, 4}};
 TwoDArray obj = new TwoDArray();
  obj.show(x);
 }
}
Output:
          Matrix x: 
          1 2 
          3 4 

In this program, the show() method is designed to accept a two-dimensional array as its argument and does not return value.

The purpose of this method is to print elements of two-dimensional array passed to it. The statement obj.show(x); displays the elements of two dimensional array on the console.


Hope that this tutorial has covered almost all the important points related to passing arrays to methods in java with example programs. I hope that you will have understood how to pass one-dimensional and two-dimensional arrays to a method in java.

Thanks for reading!!!