Do these 3 things before closing this tab:
1Repair Windows errors before they cause bigger problems2Fix the driver behind crashes, sound loss and screen glitches3Clear out junk files and repair common Windows errorsiTechGuides is reader-supported. When you buy through links on our site, we may earn an affiliate commission. As an Amazon Associate I earn from qualifying purchases. Learn more
A jagged array in Java is an array of arrays whose nested arrays can have different lengths. For example, an int[][] can contain rows with 3, 2, and 4 integers. Java has no separate JaggedArray type: jagged, ragged, and irregular array describe the shape of an ordinary nested array.
Java developers commonly use jagged arrays for triangular data, variable-length groups, graph adjacency lists, and other structures where every row does not need the same number of elements.
Key takeaways
- A Java jagged array is an array whose component elements are themselves arrays, so each nested row can have a different length.
- For an
int[][],array.lengthcounts rows, whilearray[row].lengthcounts the elements in the current row. new int[rows][]creates the outer array but leaves each row referencenulluntil the rows are allocated.- A jagged array must be traversed using the current row’s length, not a shared column count such as
array[0].length. - Rows have fixed lengths after creation, so frequently growing or shrinking data is often better represented by
ArrayList<ArrayList<T>>. - Java’s
T[][]syntax represents nested arrays rather than one guaranteed rectangular, contiguous matrix.
What is a jagged array in Java?
A jagged array in Java is an array of nested arrays whose nested arrays do not all have to be the same length. The following int[][] contains three rows with lengths 3, 2, and 4:
Recommended Free Tools
int[][] numbers = {
{1, 2, 3},
{4, 5},
{6, 7, 8, 9}
};
The structure looks like this:
Row 0: 1 2 3
Row 1: 4 5
Row 2: 6 7 8 9
The declared type is still int[][]. Java does not define a separate language type named JaggedArray. “Jagged array,” “ragged array,” and “irregular array” are descriptive terms for a nested array whose rows vary in length.
Popular on Amazon
The Java Language Specification’s array rules define a multidimensional array as an array whose component type can itself be an array. The official Java arrays tutorial likewise explains that a two-dimensional Java array is an array whose components are arrays and that those rows can vary in length.
How does Java represent a multidimensional array?
Java’s multidimensional-array syntax is built from nested arrays. An int[][] is an outer array containing references to int[] objects:
int[][] data
|
+-- int[] row 0
+-- int[] row 1
+-- int[] row 2
That model explains the three common expressions:
data.lengthis the number of elements in the outer array—in a row-oriented example, the number of rows.data[row].lengthis the length of one particular nestedint[].data[row][column]first selects a row and then selects an element within that row.
For example:
int[][] values = {
{10, 20, 30},
{40, 50}
};
System.out.println(values.length); // 2 rows
System.out.println(values[0].length); // 3 elements
System.out.println(values[1].length); // 2 elements
System.out.println(values[0][1]); // 20
System.out.println(values[1][0]); // 40
int[] secondRow = values[1];
System.out.println(secondRow[0]); // 40
values[1] is an int[], not an individual integer. The second index is required to select an integer from that row.
What’s actually slowing this PC down?
Pick the symptom - the matching free tool is one click away.
Array indexes are zero-based. An index outside the valid range causes an ArrayIndexOutOfBoundsException, and a row reference that is null causes a NullPointerException when code tries to read its length or an element. These behaviors are specified in the Java Language Specification.
How do you create a jagged array in Java?
Using an array initializer
The shortest approach is a nested initializer. Java creates the outer array and each row from the supplied values:
int[][] jagged = {
{1, 2, 3},
{4, 5},
{6, 7, 8, 9}
};
The resulting row lengths are 3, 2, and 4. The array length is fixed after creation, as are the lengths of the individual row arrays.
Allocating the outer array first
Use new int[rows][] when the row lengths are known separately or will be determined later:
int[][] jagged = new int[3][];
jagged[0] = new int[3];
jagged[1] = new int[2];
jagged[2] = new int[4];
This code creates an outer array with three slots. Each slot initially contains null; the three assignments then replace those null references with rows of different lengths. Newly allocated int elements contain Java’s default value, 0.
Allocating and populating rows
You can create each row with its values immediately:
int[][] jagged = new int[3][];
jagged[0] = new int[] {10, 20, 30};
jagged[1] = new int[] {40, 50};
jagged[2] = new int[] {60, 70, 80, 90};
Rows can also be created programmatically from input:
Also popular on Amazon
int[][] groups = new int[3][];
int[] firstGroup = {2, 4};
int[] secondGroup = {1, 3, 5, 7};
int[] thirdGroup = {9};
groups[0] = firstGroup;
groups[1] = secondGroup;
groups[2] = thirdGroup;
Declaring a variable does not allocate an array object. Allocation happens with new or with an array initializer. The Java arrays tutorial covers these declaration, initialization, and access rules.
How do you traverse a jagged array safely?
The inner loop must use the length of the row currently being processed:
int[][] jagged = {
{1, 2, 3},
{4, 5},
{6, 7, 8, 9}
};
for (int row = 0; row < jagged.length; row++) {
for (int column = 0; column < jagged[row].length; column++) {
System.out.print(jagged[row][column] + " ");
}
System.out.println();
}
The output is:
1 2 3
4 5
6 7 8 9
This is incorrect for a genuinely jagged structure:
for (int row = 0; row < jagged.length; row++) {
for (int column = 0; column < jagged[0].length; column++) {
System.out.println(jagged[row][column]);
}
}
The incorrect version assumes every row has the length of row 0. When a later row is shorter, the code can throw ArrayIndexOutOfBoundsException.
Using enhanced for loops
Enhanced loops are clearer when you do not need row or column indexes:
Outdated Drivers Are Slowing You Down
One free scan finds every outdated or missing driver and matches the right update for your exact hardware.Free scan · exact hardware matchWindows Errors? Fix Them Before They Spread
Repair common Windows errors and clear accumulated junk for a smoother, more stable PC - no reinstall needed.Free scan · no reinstallfor (int[] row : jagged) {
for (int value : row) {
System.out.print(value + " ");
}
System.out.println();
}
The enhanced loop receives one nested int[] at a time and then one integer from that row. If null rows are possible, add a check before starting the inner loop.
How do you print a jagged array?
Calling System.out.println(jagged) does not print nested contents. It prints an object identity-style representation. Use Arrays.deepToString for a readable one-line representation:
import java.util.Arrays;
int[][] jagged = {
{1, 2, 3},
{4, 5},
{6, 7, 8, 9}
};
System.out.println(Arrays.deepToString(jagged));
Output:
[[1, 2, 3], [4, 5], [6, 7, 8, 9]]
The Java SE 26 Arrays API documentation provides deepToString for producing a string representation of nested arrays. Use nested loops instead when you need custom formatting, row labels, or one value per line.
What is the difference between a jagged and rectangular array?
A rectangular-looking array has the same number of elements in every row at the time it is created. A jagged array allows each row to have its own length. Both structures use the same Java type, such as int[][].
Quick wins for a faster PC:
Scan for outdated or missing drivers - takes under a minuteDriver Scan →Clear out junk files and repair common Windows errorsFree Scan →| Characteristic | Rectangular-looking array | Jagged array |
|---|---|---|
| Java type | int[][] |
int[][] |
| Number of rows | Fixed after outer-array creation | Fixed after outer-array creation |
| Row lengths | Initially identical | May differ |
| Typical allocation | new int[rows][columns] |
new int[rows][], followed by separate row allocation |
| Element access | array[row][column] |
array[row][column] |
| Inner-loop bound | A shared column count can be used if the shape is enforced | Use array[row].length |
| Unused cells | Often represented by default values such as 0 |
Can be omitted by making rows shorter |
Create a rectangular-looking array like this:
int[][] rectangle = new int[3][4];
The expression initially creates three rows, each containing four integer elements. Create a jagged array like this:
Also popular on Amazon
int[][] jagged = new int[3][];
jagged[0] = new int[2];
jagged[1] = new int[4];
jagged[2] = new int[1];
The difference is structural rather than a difference in declared type. Java array lengths are not part of the array type, so int[3][4] and int[3][2] are both represented by the type int[][]. The Java Language Specification describes array lengths as properties of array objects rather than components of their types.
A rectangular-looking array is not permanently protected from becoming jagged. Because each row is a separate array reference, code can later replace one row with an array of another length. The NIST report on Java numerical computing discusses this shape limitation of Java’s array-of-arrays representation.
How do you handle null and empty rows?
A null row and an empty row are different states. A null row has no row array at all; an empty row is a real array with length zero:
int[][] data = new int[2][];
data[0] = null;
data[1] = new int[0];
System.out.println(data[0] == null); // true
System.out.println(data[1].length); // 0
This is unsafe because data[0] is null:
System.out.println(data[0].length); // NullPointerException
Use a null check when a missing row is meaningful:
for (int row = 0; row < data.length; row++) {
if (data[row] == null) {
System.out.println("Row " + row + " is missing");
continue;
}
for (int value : data[row]) {
System.out.print(value + " ");
}
System.out.println();
}
An enhanced loop also needs a null check:
for (int[] row : data) {
if (row != null) {
System.out.println(row.length);
}
}
A nested initializer can also contain null row references. The Java Language Specification documents nested array initialization and the null behavior that follows when code dereferences a null nested array.
What are common jagged-array errors?
Using the wrong length
Use jagged.length for the outer array and jagged[row].length for the current row. Do not use one row’s length as the universal column count unless the program has explicitly validated a rectangular invariant.
Confusing length with length()
Arrays expose a length field:
jagged.length;
jagged[row].length;
length() is a method used by types such as String; it is not how Java reads an array length.
Accessing a nonexistent index
For a row of length 2, valid indexes are 0 and 1. Accessing row[2] throws ArrayIndexOutOfBoundsException. The outer index must also be within 0 through jagged.length - 1.
Assuming rows are automatically resizable
Every array length is fixed after that array object is created. To replace a row with a larger or smaller capacity, allocate a new row and assign it:
int[][] data = {
{1, 2},
{3, 4}
};
data[0] = new int[] {1, 2, 5, 6};
Accidentally sharing one row
Rows are references. Assigning the same inner array to two outer positions makes both positions refer to the same data:
int[] shared = {1, 2, 3};
int[][] data = new int[2][];
data[0] = shared;
data[1] = shared;
data[0][0] = 99;
System.out.println(data[1][0]); // 99
The second row prints 99 because it is not an independent copy. Allocate each row separately when changes to one row must not affect another. Row aliasing is one of the important consequences of Java’s array-of-arrays model, as described by NIST’s Java numerical-computing report.
Also popular on Amazon
Making only a shallow copy
Cloning the outer array does not clone its nested rows:
The Tool Desk
Outbyte Driver Updater FREEScan for outdated or missing drivers - takes under a minuteDriver Scan →Outbyte PC Repair FREERepair Windows errors before they cause bigger problemsFix Now →int[][] original = {
{1, 2},
{3, 4}
};
int[][] copy = original.clone();
copy[0][0] = 99;
System.out.println(original[0][0]); // 99
The outer array is new, but copy[0] and original[0] still refer to the same row. Make a row-by-row copy when independent nested data is required:
int[][] deepCopy = new int[original.length][];
for (int i = 0; i < original.length; i++) {
deepCopy[i] = original[i] == null
? null
: original[i].clone();
}
The Java Language Specification describes array cloning, including the shallow-copy behavior of multidimensional arrays.
What are practical uses for jagged arrays?
Jagged arrays fit data whose groups naturally contain different numbers of values. The following examples illustrate appropriate models, not rules that a jagged array is always the best choice.
Triangular data
int[][] triangle = {
{1},
{2, 3},
{4, 5, 6},
{7, 8, 9, 10}
};
Each row represents one level of a triangle, so allocating unused cells for a rectangle would not reflect the data’s natural shape.
Free tools Windows power users keep installed
One-click scans. No signup required.
Variable numbers of test scores
int[][] testScores = {
{85, 90},
{78, 81, 88, 92},
{95}
};
Each row can represent one student or group, while the row length represents how many scores are available.
Graph adjacency lists
int[][] graph = {
{1, 2}, // Node 0 connects to nodes 1 and 2
{0, 3}, // Node 1 connects to nodes 0 and 3
{0}, // Node 2 connects to node 0
{1} // Node 3 connects to node 1
};
Each row lists the neighbors of one node. Different nodes can have different numbers of neighbors, making a jagged structure a natural representation.
What are the advantages and disadvantages?
| Consideration | Jagged-array effect |
|---|---|
| Variable row sizes | Each row can have exactly the length required by the data. |
| Unused rectangular cells | Shorter rows can avoid allocating cells that the data does not use. |
| Indexing | Values remain directly accessible through data[row][column]. |
| Allocation | Each row is a separate array object, in addition to the outer array and its references. |
| Resizing | Rows cannot grow in place; replacement arrays are required. |
| Shape validation | The compiler does not generally enforce equal row lengths. |
| Aliasing risk | Multiple outer positions can refer to the same row. |
| Iteration | Code must read each current row’s length and handle possible null rows. |
A jagged array may use less storage for genuinely irregular data because it can omit unused rectangular cells. That is not a universal memory guarantee: the outer array, row references, and separate row objects also consume memory.
Jagged arrays also do not guarantee better performance. Separate row objects can be useful for irregular data, while a flat representation may be preferable for some performance-sensitive rectangular algorithms. The correct choice depends on row shape, allocation behavior, access patterns, and the operations the program performs.
Should you use a jagged array or an alternative?
Choose the representation that matches the data’s shape and how the data changes.
Also popular on Amazon
| Representation | Use it when | Main trade-off |
|---|---|---|
Jagged T[][] |
Rows naturally have different fixed lengths and indexed access is useful. | Each row is separate, and traversal must handle different lengths and possible nulls. |
Rectangular T[rows][columns] |
Every row has the same number of columns and the data behaves like a grid or matrix. | Unused cells may need to be allocated, and equal shape is a program invariant rather than a distinct type guarantee. |
ArrayList<ArrayList<T>> |
Rows are built incrementally or must frequently grow and shrink. | Collection APIs add flexibility but also introduce different overhead and behavior; primitive values may require boxing. |
| Flattened one-dimensional array | The data is rectangular and compact storage or predictable scanning is important. | Index calculations reduce readability and variable row lengths require extra offset metadata. |
Use a rectangular array for a true grid
An 8-by-8 board is naturally rectangular:
int[][] board = new int[8][8];
Algorithms that repeatedly use a common row and column shape are usually simpler with a rectangular representation. A program can validate a rectangular invariant, but int[][] itself does not prevent a later row replacement with a different length.
Use ArrayList for frequently changing rows
Use nested lists when groups are assembled incrementally:
ArrayList<ArrayList<Integer>> groups = new ArrayList<>();
groups.add(new ArrayList<>());
groups.get(0).add(42);
Nested lists provide operations such as add, remove, and size. The trade-off is that lists have collection-specific overhead and APIs, and Integer values can introduce boxing compared with primitive int[] rows.
Use a flat array for a rectangular performance-oriented structure
A rectangular 3-by-4 structure can be represented with one array:
int rows = 3;
int columns = 4;
int[] flat = new int[rows * columns];
int row = 2;
int column = 1;
int index = row * columns + column;
flat[index] = 42;
The flat form requires index arithmetic and does not naturally represent variable-length rows. Use additional offsets or lengths if the data is irregular.
What is a complete runnable jagged-array example?
The following program creates, prints, measures, traverses, and indexes a jagged array:
import java.util.Arrays;
public class JaggedArrayExample {
public static void main(String[] args) {
int[][] scores = {
{90, 85, 88},
{76, 81},
{95, 91, 89, 97}
};
System.out.println("Complete array:");
System.out.println(Arrays.deepToString(scores));
System.out.println("\nRows and lengths:");
for (int row = 0; row < scores.length; row++) {
System.out.println(
"Row " + row + " has " + scores[row].length + " elements"
);
}
System.out.println("\nElements:");
for (int[] row : scores) {
for (int score : row) {
System.out.print(score + " ");
}
System.out.println();
}
System.out.println("\nIndividual value:");
System.out.println(scores[2][3]); // 97
}
}
Expected output:
Complete array:
[[90, 85, 88], [76, 81], [95, 91, 89, 97]]
Rows and lengths:
Row 0 has 3 elements
Row 1 has 2 elements
Row 2 has 4 elements
Elements:
90 85 88
76 81
95 91 89 97
Individual value:
97
Frequently Asked Questions
Is int[][] always a jagged array in Java?
int[][] is an array of arrays and can be jagged, but the type alone does not tell you whether all rows currently have equal lengths. An array created with new int[3][4] starts rectangular-looking, while an array created with separately sized rows is jagged.
Can a jagged array contain a null row?
Yes. new int[3][] creates three null row references until code assigns arrays to them. Check row != null before reading row.length or accessing a row element.
How do you find the longest row in a jagged array?
Iterate over the rows and keep the largest non-null row length:
int longest = 0;
for (int[] row : data) {
if (row != null && row.length > longest) {
longest = row.length;
}
}
Are Java 2D arrays contiguous in memory?
Ordinary Java T[][] values are nested arrays: an outer array refers to separate row arrays. They are therefore not one guaranteed contiguous two-dimensional primitive block. A flattened one-dimensional array is the direct alternative when one rectangular buffer is required.
How do you copy a jagged array without sharing its rows?
Clone or copy each row individually. Cloning only the outer array is shallow, so the original and copy continue to share the nested row arrays.
The Bottom Line
A jagged array in Java is an int[][], double[][], or similar nested-array structure whose rows can have different lengths. Use array[row].length while traversing, distinguish null rows from empty rows, and choose a rectangular array, nested lists, or a flat array when those alternatives better match the data or access pattern.

