Java 2D Array rows vs cols syntax question

Viewed 55

I am having a hard time understanding why putting brackets versus leaving them out either calls for the rows or cols in a 2D array. I get the syntax I just don't understand why it works that way? Should I just not worry about it and move on with my life?

double[][] values = {
                 {1.2, 9.0, 3.2},
                 {8.2, 8.6, -1.2},
                 {-7.3, 2.5, 9.7},
                 {4.1, 7.0, 5.1},
            };
            
            System.out.println("Number of Rows: " + values.length);

            System.out.println("Number of Cols: " + values[0].length);

2 Answers

a 2D array is an array of arrays. The variable length returns the number of elements in the array.

so values.length gives the number of elements in the outer array which are the inner arrays (rows)

and values[0].length gives the number of elements in the first inner array (columns)

values.length gives you the length of the outer array. That is the array containing 4 rows. The outer array happens to contain objects that are themselves arrays.

values[0].length gives you the length of the 1st (0th) object in the outer array. This 1st object is itself an array. Since your 2D array is rectangular, every row has the same number of elements, or columns. So getting the length of any one of them will give you the number of columns

Hope that's clearer!

Related