Passing array to method in Java


Just as you can pass primitive type values to methods, you can also pass arrays to methods. For example, the following method displays the elements in an int array -

Example

public static void printArray(int[] array) {
   for (int i = 0; i < array.length; i++) {
      System.out.print(array[i] + " ");
   }
}

You can invoke it by passing an array. For example, the following statement invokes the print Array method to display 3, 1, 2, 6, 4, and 2 -

printArray(new int[]{3, 1, 2, 6, 4, 2});

Updated on: 25-Feb-2020

201 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements