javaarrayscall-by-value

I was trying to directly send in values to my array as parameter but it does not work


It works if I initialize those values in another array and then pass it in the main function. Is it something that I am doing wrong or is it just we cannot directly pass values? Here are both the codes:- Using Array to Pass:-

public class DDArray {
    void array(int[][] a){
        int x=a.length;
        int y=a[0].length;
        for(int i=0;i<x;i++){
            for(int j=0;j<y;j++){
                System.out.print(a[i][j] + " ");
            }
            System.out.println();
        }
    }
    public static void main(String args[]){
        DDArray ob=new DDArray();
        int[][] b={{1,2,3,4,5},{11,22,33,44,55}};
        ob.array(b);
    }
}

Directly Passing:-

public class DDArray {
    void array(int[][] a){
        int x=a.length;
        int y=a[0].length;
        for(int i=0;i<x;i++){
            for(int j=0;j<y;j++){
                System.out.print(a[i][j] + " ");
            }
            System.out.println();
        }
    }
    public static void main(String args[]){
        DDArray ob=new DDArray();
        ob.array({{1,2,3,4,5},{11,22,33,44,55}});
    }
}

Solution

  • Change in direct call from ob.array({{1,2,3,4,5},{11,22,33,44,55}}); to ob.array(new int[][] { { 1, 2, 3, 4, 5 }, { 11, 22, 33, 44, 55 } });