Common Pitfalls: Length and NullPointerException
What you'll learn: How to distinguish between array dimensions and avoid crashes when working with jagged arrays.
Understanding array.length vs array[i].length
When working with multidimensional arrays, it's easy to confuse which length property you're accessing. Remember:
array.lengthgives you the number of rows (first dimension)array[i].lengthgives you the number of columns in rowi(second dimension)
Example:
int[][] grid = new int[3][5];
System.out.println(grid.length); // 3 (rows)
System.out.println(grid[0].length); // 5 (columns in first row)
Think of it like apartment buildings: array.length tells you how many floors exist, while array[i].length tells you how many apartments are on floor i.
The Null Row Trap
With jagged arrays, you can create the outer array without immediately creating the inner arrays. This leads to a dangerous pitfall:
int[][] jagged = new int[3][]; // Three null rows!
// This crashes with NullPointerException:
// System.out.println(jagged[0].length);
// You must initialize each row first:
jagged[0] = new int[4];
jagged[1] = new int[2];
jagged[2] = new int[3];
// Now this works:
System.out.println(jagged[0].length); // 4
Each element in the outer array starts as null until you assign an actual array to it. Trying to access .length on null causes a NullPointerException.
Always check or initialize rows before accessing their properties!
Key Takeaway: In multidimensional arrays, array.length counts rows while array[i].length counts columns; in jagged arrays, always ensure rows are initialized (not null) before accessing their length or elements.