Friday, December 27, 2024
Google search engine
HomeLanguagesJavaHow to Pass an Array to a Function in Java?

How to Pass an Array to a Function in Java?

Passing an array to a function is an easy-to-understand task in java. Let function GFG() be called from another function GFGNews(). Here, GFGNews is called the “Caller Function” and GFG is called the “Called Function OR Callee Function”. The arguments/parameters which GFGNews passes to GFG are called “Actual Parameters” and the parameters in GFG are called “Formal Parameters”. The array to pass can be a one-dimensional(1D) array or a multi-dimensional array such as a 2D or 3D array. The Syntax to Pass an Array as a Parameter is as follows:

Caller Function:

called_function_name(array_name);

The code for the called function depends on the dimensions of the array.

The number of square brackets in the function prototype is equal to the dimensions of the array, i.e. [n] for 1D arrays, [n][n] for 2D arrays, [n][n][n] for 3D arrays, and so on.

Called Function:

// for 1D array
returnType functionName(datatype[] arrayName) {
    //statements
}

OR

// for 1D array
returnType functionName(datatype arrayName[]) {
    //statements
}

Similarly, for 2D Arrays, the Syntax would be:

// for 2D array
returnType functionName(datatype[][] arrayName) {
    //statements
}

OR

// for 2D array
returnType functionName(datatype arrayName[][]) {
    //statements
}

Here:

  • returnType: the return type of the called function
  • functionName: name of the called function
  • datatype: the datatype of the array
  • arrayName: name of the array

Example:

Java




import java.io.*;
  
class GFG {
      void function1(int[] array) {
        System.out.println("The first element is: " + array[0]);
    }
    void function2(int[][] array) {
        System.out.println("The first element is: " + array[0][0]);
    }
  
    public static void main(String[] args) {
        
        // creating instance of class
        GFG obj = new GFG();
  
        // creating a 1D and a 2D array
        int[] oneDimensionalArray = { 1, 2, 3, 4, 5 };
        int[][] twoDimensionalArray = { { 10, 20, 30 },
                                        { 40, 50, 60 },
                                        { 70, 80, 90 } };
        
        // passing the 1D array to function 1
        obj.function1(oneDimensionalArray);
        
        // passing the 2D array to function 2
        obj.function2(twoDimensionalArray);
    }
}


Output

The first element is: 1
The first element is: 10
Dominic Rubhabha-Wardslaus
Dominic Rubhabha-Wardslaushttp://wardslaus.com
infosec,malicious & dos attacks generator, boot rom exploit philanthropist , wild hacker , game developer,
RELATED ARTICLES

Most Popular

Recent Comments