Site icon TestingDocs.com

How to pass an array to a method in Java

Overview

In Java, methods are used to break the Java program into small modules. These methods are used to call from other methods. The caller method can pass data to the methods as parameters. The data that is being passed from the caller or invoking method to the method. The method can return data to the caller method using the return value.

Passing Array to Method in Java

An array can be passed to a method similar to how we pass primitive data type arguments. The primitive data type arguments are those like int or double which are passed into methods by values.

The method prototype must match with the argument of the array.

public <return_type> methodName(int[] passedArray);

Example:

public static void printArray(int[] printArray) {

…// method body

}

The main method invokes the method using the statement:

printArray(marks);

To pass an array as an argument to a method is to pass the name of the array without the square brackets.

Code Listing

package com.testingdocs.tutorial;
// Pass an array to a method demo.
// www.TestingDocs.com
public class PassAnArraytoMethodDemo {

  public static void main(String[] args) {
    //declaring an array 
    int marks[]= {65,70,58,90};
    System.out.println("Original Array:=");
    printArray(marks);
    //Every element should be incremented by 5
    System.out.println("Modified Array:=");
    int modifiedArray[] = methodToModifyArray(marks);
    printArray(modifiedArray);
  }

  //method to modify the array.
  public static int[] methodToModifyArray(int[] marksArray) {
    for(int i=0; i<marksArray.length; i++)
    {
      //just to modify the array inside the method.
      marksArray[i]=marksArray[i] + 5;
    }
    return marksArray;
  }

  //method to print array.
  public static void printArray(int[] printArray) {
    for(int i=0; i<printArray.length; i++)
    {
      //print the modified array
      System.out.println(printArray[i]);
    }
  }

}

 

Program output

Original Array:=
65
70
58
90
Modified Array:=
70
75
63
95

 

Exit mobile version