Java Work with Rows of Different Lengths
A Java two-dimensional array is an array whose elements are arrays. Rows can have different lengths, and a row reference can be null.
Understand the idea
Do not assume that every row has the same number of columns just because a declaration uses two bracket pairs. Visit each row according to its own length and decide whether missing rows are valid. A rectangular table may be better represented by a domain-specific structure if rows, columns and invariants carry more meaning than raw positions.
Run it locally
Use a local JDK 21 or newer. Save the complete example as Main.java in a separate lab folder, then compile and run it with the commands below. Java examples do not run in Bhylu’s browser playground. The -ea option enables assertion checks used by some lessons.
javac --release 21 -encoding UTF-8 -d out Main.java
java -ea -cp out MainA worked example
public class Main {
public static void main(String[] args) {
int[][] bookings = {{3, 2}, {5}, {1, 1, 2}};
for (int[] day : bookings) {
int total = 0;
for (int count : day) total += count;
System.out.println(total);
}
}
}
Expected output
5
5
4Each row represents one day’s session bookings and has its own number of entries. The inner loop naturally adapts to that row. An indexed version would need bookings[row].length as the column limit, not the outer array’s length. This example intentionally includes a short middle row to expose that difference.
Check the official Java documentation for detailed contracts and supported options.