How do multidimensional arrays work in Java, and how do they differ from truly rectangular arrays in languages like C?
Short answer
Java doesn't have true multidimensional arrays in the C sense; a 2D array (int[][]) is actually an array of arrays, where each row is an independently allocated one-dimensional array object -- this means rows can have different lengths (a "jagged" array), unlike a genuinely…
Advertisement
AModel answer
Java doesn't have true multidimensional arrays in the C sense; a 2D array (int[][]) is actually an array of arrays, where each row is an independently allocated one-dimensional array object -- this means rows can have different lengths (a "jagged" array), unlike a genuinely rectangular structure, and each row must be individually instantiated or accessed via nested indexing, with memory layout reflecting this array-of-arrays structure rather than one contiguous rectangular block.
int[][] matrix = new int[3][4]; // 3 rows, each with 4 columns (rectangular)
matrix[1][2] = 99;
int[][] jagged = new int[3][]; // 3 rows, columns not yet specified
jagged[0] = new int[2];
jagged[1] = new int[5]; // different length than row 0 -- legal, since it's an array of arrays
jagged[2] = new int[1];Real-world example
A program modeling a triangular data structure (like Pascal's triangle, where each row has one more element than the previous) uses a jagged array where each row is deliberately allocated with a different length, taking advantage of Java arrays not being required to be rectangular.
Likely follow-ups
- How would you iterate a jagged array safely without an IndexOutOfBoundsException from assuming uniform row length?
- What's the memory/performance implication of the array-of-arrays structure versus a true contiguous 2D block?
Related topics