0Pricing
Java Academy · Lesson

Jagged Arrays & Table Formatting

Handle jagged 2D arrays and print aligned tables using per-column widths; demo builds a sample matrix without Scanner.

Jagged Concept

Jagged 2D arrays: each row can have a different length. Treat rows separately, never assume a common column count.

Create Jagged

Create a jagged array by allocating rows with different lengths. The message explains why: we only need as many columns as each row requires.

public class Main {
  public static void main(String[] args) {
    // Create a jagged array with 3 rows of varying lengths
    int[][] m = new int[3][];

    // Row 0 has 2 columns
    m[0] = new int[]{1, 2};

    // Row 1 has 3 columns
    m[1] = new int[]{3, 4, 5};

    // Row 2 has 1 column
    m[2] = new int[]{6};

    // Print the jagged array
    System.out.println("Jagged array contents:");
    for (int r = 0; r < m.length; r++) {
      for (int c = 0; c < m[r].length; c++) {
        System.out.print(m[r][c] + " ");
      }
      System.out.println(); // new line after each row
    }
  }
}

All lessons in this course

  1. 2D Array Basics & Nested Iteration
  2. Jagged Arrays & Table Formatting
  3. Row/Column Maxima, Transpose & Formatting
  4. 2D Mini-Project: Gradebook
  5. 2D Utilities as a Helper Class (Refactor)
  6. 2D Data Cleaning & Validation
← Back to Java Academy