The following java code is giving output 1 2 3 .How the code is executed?

Vaibhav :

How in this code for loop is running three times, as here argcopy array size is 2 and as per my knowledge once an array is created its size can't be changed.

class test {                                     //line 1
    public static void main(String[] args) {     //line 2
        String[][] argcopy = new String[2][2];   //line 3
        String arg[] = new String[3];            //line 4
        int x;                                   //line 5
        arg[0] = "1";                            //line 6
        arg[1] = "2";                            //line 7
        arg[2] = "3";                            //line 8
        argcopy[0] = arg;                        //line 9
        x = argcopy[0].length;                   //line 10
        for (int y = 0; y < x; y++)
        {
            System.out.println(" " + argcopy[0][y]);   //line 11
        }
    }
}
WJS :

A 2D array is simply an array of arrays. This means you don't even have to allocate storage for the second dimension. This also permits you to have ragged arrays which is demonstrated below.

      int[][] raggedArray = new int[5][];
      raggedArray[0] = new int[]{1,2,3};
      raggedArray[1] = new int[]{4,5,6,7,8,9};
      raggedArray[2] = new int[]{10,12,13,14};
      raggedArray[3] = new int[]{15};
      raggedArray[4] = new int[]{16,17,18,19,20};
      for (int[] array : raggedArray) {
         System.out.println(Arrays.toString(array));
      }

Each new array is simply an object which is assigned to the desired location.

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=310810&siteId=1