0
public class CommandArgsThree 
{
    public static void main(String [] args) 
    {
        String [][] argCopy = new String[2][2];
        int x;
        argCopy[0] = args;
        x = argCopy[0].length;
        for (int y = 0; y < x; y++) 
        {
            System.out.print(" " + argCopy[0][y]);
        }
    }
}

and the command-line invocation is: java CommandArgsThree 1 2 3

1.what is the difference between the above command and this: java CommandArgsThree 123,what is the args type and its behavior regarding the different inputs.

String [][] argCopy = new String[2][2];

2.does the above statement creates an two dimensional array of strings i.e it

null null
null null

as this can be accessed by argCopy[0][0],argCopy[0][1] or

{null,null,null,null} 

as this can be accessed by argCopy[0],argCopy[1],argCopy[2],,,,.

1 Answers1

3

It seems the real misunderstanding here is regarding multi-dimensional arrays.

A 2 dimensional array is an array whose elements are references to 1 dimensional arrays.

When you initialize your array with

String [][] argCopy = new String[2][2];

you get an array that contains two arrays (rows), each having two elements (columns). The values of your array are all null by default.

When you assign

argCopy[0] = args;

The first row of your 2D array now refers to a different array than it originally referred to. Now the first row of argCopy contains 3 String elements (assuming you passed 3 parameters to the command line, as in CommandArgsThree 1 2 3), that can be accessed with argCopy[0][0], argCopy[0][1] and argCopy[0][2], and the second row still contains the original 2 null values.

When you pass a single parameter to the command line (as in CommandArgsThree 123), the args array contains a single String element, so after the assignment argCopy[0] = args;, the first row of argCopy contains 1 String.

Eran
  • 387,369
  • 54
  • 702
  • 768