Programming Tutorials

Array used as a parameter in Java

By: Gayathri in Java Tutorials on 2007-05-18  

In Java, an array can be passed as a parameter to a method just like any other data type. The array parameter should be declared with square brackets [] after the type of the array elements.

Here is an example program that demonstrates passing an array as a parameter in Java:

public class ArrayExample {
    public static void main(String[] args) {
        int[] numbers = {1, 2, 3, 4, 5};
        printArray(numbers);
    }

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

In the above program, we have a method named printArray that takes an integer array as a parameter. Inside the method, we are iterating through the array and printing its elements. In the main method, we have created an integer array and passed it as an argument to the printArray method. This will print all the elements of the array passed as a parameter.






Add Comment

* Required information
1000

Comments

No comments yet. Be the first!

Most Viewed Articles (in Java )

Latest Articles (in Java)