pass array to method Java

Viewed 342208

How can I pass an entire array to a method?

private void PassArray() {
    String[] arrayw = new String[4];
    //populate array
    PrintA(arrayw[]);
}

private void PrintA(String[] a) {
    //do whatever with array here
}

How do I do this correctly?

10 Answers

If you are too lazy ;) to declare variable.

import static org.junit.Assert.assertEquals
public class BinarySearch 
{

    public static void main(String[] args) 
    {
        search(new int[] {-1,0,3,5,9,12}, 9); //creating and passing array
    }
    public static int search(int[] nums, int target) 
    {
        //write some code
        return -1;
    }
}

This is very useful for unit test like below

assertEquals(4,search(new int[] {-1,0,3,5,9,12}, 9));
assertEquals(-1,search(new int[]{-1,0,3,5,9,12}, 2));
class test
{
    void passArr()
    {
        int arr1[]={1,2,3,4,5,6,7,8,9};
        printArr(arr1);
    }

    void printArr(int[] arr2)
    {
        for(int i=0;i<arr2.length;i++)
        {
            System.out.println(arr2[i]+"  ");
        }
    }

    public static void main(String[] args)
    {
        test ob=new test();
        ob.passArr();
    }
}
Related