How to Pass Array to Method in Java: Syntax and Examples
In Java, you can pass an array to a method by specifying the array type in the method parameter, like
void methodName(int[] arr). Then, call the method by passing the array variable, for example, methodName(myArray).Syntax
To pass an array to a method, declare the method parameter with the array type. For example, int[] arr means the method expects an array of integers. When calling the method, pass the array variable directly.
- Method declaration: specifies the array parameter
- Method call: passes the actual array
java
public void methodName(int[] arr) { // use arr inside method } // Calling the method int[] myArray = {1, 2, 3}; methodName(myArray);
Example
This example shows a method that receives an integer array and prints each element. It demonstrates how to pass the array and use it inside the method.
java
public class ArrayExample { public static void printArray(int[] numbers) { for (int num : numbers) { System.out.println(num); } } public static void main(String[] args) { int[] myNumbers = {10, 20, 30, 40}; printArray(myNumbers); } }
Output
10
20
30
40
Common Pitfalls
Common mistakes include:
- Passing the array length or elements instead of the array variable.
- Declaring the method parameter incorrectly, such as missing the array brackets.
- Modifying the array inside the method without understanding that arrays are passed by reference.
Always pass the array variable and declare the parameter with brackets [].
java
public class PitfallExample { // Wrong: parameter missing [] // public static void wrongMethod(int arr) { } // Correct: public static void correctMethod(int[] arr) { for (int i = 0; i < arr.length; i++) { arr[i] = arr[i] * 2; // modifies original array } } public static void main(String[] args) { int[] data = {1, 2, 3}; correctMethod(data); for (int num : data) { System.out.println(num); // prints 2, 4, 6 } } }
Output
2
4
6
Quick Reference
Remember these tips when passing arrays to methods:
- Use
type[] namein method parameters. - Pass the array variable directly when calling the method.
- Arrays are passed by reference, so changes inside the method affect the original array.
Key Takeaways
Declare method parameters with array brackets, e.g.,
int[] arr, to accept arrays.Pass the array variable directly when calling the method, like
methodName(myArray).Arrays are passed by reference, so changes inside the method affect the original array.
Avoid passing individual elements or array length instead of the whole array.
Always match the array type in the method parameter with the array you pass.