Matrix Programs in Java: Addition, Multiplication, Transpose, Spiral and Rotation
The five classic Java matrix programs on a plain int[][]: addition, multiplication, transpose, spiral order and 90-degree rotation, each with a diagram, a dry run and real JDK 25 output, plus six mistakes that lose marks (an unchanged transpose, a spiral that repeats numbers, a silent int overflow) and operation counts for the complexity question.
Almost every Java lab sheet and campus-placement paper asks the same five matrix questions: add two matrices, multiply them, transpose one, print one in spiral order, rotate one by 90 degrees. They look like five separate problems. They are one idea — a grid of numbers addressed by a row number and a column number — wearing five different loop shapes.
This page builds all five from scratch on a plain int[][], in the order a first-year student meets them. Each program comes with a picture of what it does, the real code from the repository, a dry run, and the exact output the code printed on Java 25. The mistakes that cost marks (an unchanged transpose, a spiral that repeats numbers, a product that throws) are reproduced on purpose, so you can recognise them in your own code.
Tested against: Temurin JDK 25.0.5+8 (Java 25, an LTS release), JUnit 6.1.3 (latest GA on Maven Central) and Maven 3.9.11. There are no dependencies beyond JUnit, and every console line below is copied from a file that the test run wrote, in the matrix module of the companion repository.
A Java matrix is an array of arrays, and that explains half the bugs
When you write new int[2][3], Java does not allocate one block of six numbers. It allocates one outer array of two slots, and each slot points to its own inner int[3]. There is no true two-dimensional array in the language; there are only arrays whose elements happen to be arrays.
The picture carries two consequences you will keep running into. First, nothing forces the rows to be the same length, so a matrix can be “jagged”, and the programs below check for that before doing anything. Second, copying the outer array copies the two references and not the rows, so a “copy” and the original share every number.
Throughout this post a matrix has m.length rows and m[0].length columns. The repository’s guard rejects empty and jagged input, and a deep copy makes new rows. Both are in MatrixBasics.java.
public static void requireRectangular(int[][] m) {
if (m.length == 0 || m[0].length == 0) {
throw new IllegalArgumentException("matrix must have at least one row and one column");
}
for (int i = 1; i < m.length; i++) {
if (m[i].length != m[0].length) {
throw new IllegalArgumentException("row " + i + " has " + m[i].length
+ " columns but row 0 has " + m[0].length);
}
}
}
public static int[][] copyOf(int[][] a) {
int[][] copy = new int[a.length][];
for (int i = 0; i < a.length; i++) {
copy[i] = a[i].clone();
}
return copy;
}
5. 'copy' made with clone() is shallow
original = [[1, 2], [3, 4]]; copy = original.clone(); copy[0][0] = 99
original[0][0] is now 99 (the rows are shared)
copyOf() makes new rows: changing deep[1][1] left original[1][1] at 4
Going deeper: jagged arrays, row-major order and shallow copies
Because every row is its own object, a row is the natural unit to loop over: for (int[] row : m) touches one contiguous block at a time, while walking down a column hops between separate objects. That difference is why the multiplication section below has a second loop order. This post counts operations rather than timing them, because timings on a shared machine drift from run to run.
The same shallow-copy idea applies to every object, not just arrays; Deep Copy vs Shallow Copy in Java shows why clone() is awkward in general.
The formatting helper used in every transcript: MatrixBasics.format in MatrixBasics.java
Adding two matrices: same shape, same position
Addition is the gentlest of the five. Two matrices can be added only when they have the same number of rows and the same number of columns, and then each cell of the answer is the sum of the two cells in the same position.
The diagram highlights one cell, but the loops simply visit every position once. The code first checks the shapes, then fills a new matrix of the same size (MatrixBasics.java):
public static int[][] add(int[][] a, int[][] b) {
requireRectangular(a);
requireRectangular(b);
if (a.length != b.length || a[0].length != b[0].length) {
throw new IllegalArgumentException("cannot add " + shape(a) + " and " + shape(b)
+ ": both matrices must have the same shape");
}
int[][] sum = new int[a.length][a[0].length];
for (int i = 0; i < a.length; i++) {
for (int j = 0; j < a[0].length; j++) {
sum[i][j] = a[i][j] + b[i][j];
}
}
return sum;
}
A + B (both 2x3)
[1 2 3]
[4 5 6]
+
[6 5 4]
[3 2 1]
=
[7 7 7]
add 2x3 + 3x2 -> IllegalArgumentException: cannot add 2x3 and 3x2: both matrices must have the same shape
multiply 2x3 * 2x3 -> IllegalArgumentException: cannot multiply 2x3 by 2x3: columns of A (3) must equal rows of B (2)
add with a jagged row -> IllegalArgumentException: row 1 has 1 columns but row 0 has 2
Going deeper: subtraction, jagged input and what to return
Subtraction is addition with - in the inner loop; it is in MatrixBasics.java under the same shape rule. The programs return a new matrix rather than changing an input, which keeps the examples easy to test. Rejecting a jagged row with a message that names the row costs four lines and saves a confusing ArrayIndexOutOfBoundsException later.
The shape check and its message: MatrixBasics.add in MatrixBasics.java
Multiplying two matrices: every cell is a row dotted with a column
Multiplication is the one students get wrong most often, because it is not “cell times cell”. Each cell of the answer takes one row of the first matrix and one column of the second, multiplies the pairs, and adds them up.
The diagram builds C[0][1]. It works because the first matrix has three columns and the second has three rows, so every number in the row has a partner in the column. In general an m x n matrix times an n x p matrix gives an m x p matrix. Here is the textbook triple loop (MatrixBasics.java):
public static int[][] multiply(int[][] a, int[][] b) {
requireRectangular(a);
requireRectangular(b);
int m = a.length, n = a[0].length, p = b[0].length;
if (n != b.length) {
throw new IllegalArgumentException("cannot multiply " + shape(a) + " by " + shape(b)
+ ": columns of A (" + n + ") must equal rows of B (" + b.length + ")");
}
int[][] c = new int[m][p]; // the result shape is rows(A) x cols(B)
for (int i = 0; i < m; i++) {
for (int j = 0; j < p; j++) {
int dot = 0;
for (int k = 0; k < n; k++) {
dot += a[i][k] * b[k][j]; // row i of A dotted with column j of B
}
c[i][j] = dot;
}
}
return c;
}
X * Y (2x3 times 3x2 gives 2x2)
[1 2 3]
[4 5 6]
*
[ 7 8]
[ 9 10]
[11 12]
=
[ 58 64]
[139 154]
multiply 2x3 * 2x3 -> IllegalArgumentException: cannot multiply 2x3 by 2x3: columns of A (3) must equal rows of B (2)
Order matters. A × B and B × A are different matrices, and often only one of them exists. The 2×3 and 3×2 pair above can be multiplied in either order, but the results have different shapes (2×2 and 3×3).
Going deeper: the i-k-j loop order, silent overflow and the fastest known algorithms
The same product can be computed with the two inner loops swapped. The i-k-j version walks matrix B and the result row by row, which is usually friendlier to the CPU cache on large matrices, and it does exactly the same number of multiplications. The repository checks that both orders agree on 2,000 seeded random matrices (output/07-random-agreement.txt).
public static int[][] multiplyIkj(int[][] a, int[][] b) {
requireRectangular(a);
requireRectangular(b);
int m = a.length, n = a[0].length, p = b[0].length;
if (n != b.length) {
throw new IllegalArgumentException("cannot multiply " + shape(a) + " by " + shape(b));
}
int[][] c = new int[m][p];
for (int i = 0; i < m; i++) {
for (int k = 0; k < n; k++) {
int aik = a[i][k];
for (int j = 0; j < p; j++) {
c[i][j] += aik * b[k][j];
}
}
}
return c;
}
Plain int arithmetic wraps around without any warning. multiplyExact in MatrixBasics.java uses Math.addExact and Math.multiplyExact so an overflow throws instead; the reproduced failure is in the mistakes section below. For the same reason a factorial program needs care: see Factorial Program in Java.
Strassen’s 1969 algorithm showed that the textbook O(n3) is not optimal, and the best known asymptotic bound has since been pushed to just under n2.372. Those later algorithms are not used in practice because their constant factors are too large, which is why every course, and this post, teaches the triple loop (see the Wikipedia survey and the recent bound in arXiv 2508.01748).
Identity matrix and A * I == A: MatrixBasics.identity in MatrixBasics.java
The transpose of a matrix turns every row into a column. The element at row i, column j moves to row j, column i.
The diagram uses a 2×3 matrix on purpose: its transpose is 3×2, so the answer has a different shape and needs a new array. That is the general version (Transpose.java):
public static int[][] transpose(int[][] a) {
MatrixBasics.requireRectangular(a);
int rows = a.length, cols = a[0].length;
int[][] t = new int[cols][rows];
for (int i = 0; i < rows; i++) {
for (int j = 0; j < cols; j++) {
t[j][i] = a[i][j];
}
}
return t;
}
A square matrix can be transposed inside itself, with no second array. The inner loop starts at j = i + 1 so that only the cells above the diagonal are visited and each one is swapped with its mirror exactly once:
public static void transposeInPlace(int[][] a) {
MatrixBasics.requireRectangular(a);
if (a.length != a[0].length) {
throw new IllegalArgumentException("in-place transpose needs a square matrix but got " + MatrixBasics.shape(a));
}
int n = a.length;
for (int i = 0; i < n; i++) {
for (int j = i + 1; j < n; j++) {
int tmp = a[i][j];
a[i][j] = a[j][i];
a[j][i] = tmp;
}
}
}
The classic bug: start the inner loop at j = 0 and every pair is swapped twice, so the matrix comes back unchanged and there is no error to tell you. The reproduction is in the mistakes section below.
Going deeper: symmetric matrices and why in place needs a square
A matrix is symmetric when it equals its own transpose, and the check only has to compare the cells above the diagonal with their mirrors (Transpose.isSymmetric in Transpose.java). A 2×3 matrix cannot be transposed in place because its shape changes; the program throws and says so, as the last line of the output above shows.
Transpose is also the first half of the rotation below.
Spiral order: shrink four boundaries
To print a matrix in spiral order you walk the outer ring clockwise — across the top, down the right side, back along the bottom, up the left side — and then repeat on what is left inside. The trick is to keep four numbers, top, bottom, left and right, and to move each one inward after its side has been walked.
For a 3×4 matrix the outer ring has ten cells and two cells remain inside, so the loop body runs twice. The code (Spiral.java):
public static List<Integer> spiralOrder(int[][] a) {
MatrixBasics.requireRectangular(a);
List<Integer> out = new ArrayList<>();
int top = 0, bottom = a.length - 1, left = 0, right = a[0].length - 1;
while (top <= bottom && left <= right) {
for (int j = left; j <= right; j++) { // left to right along the top row
out.add(a[top][j]);
}
top++;
for (int i = top; i <= bottom; i++) { // top to bottom down the right column
out.add(a[i][right]);
}
right--;
if (top <= bottom) { // a row may be left over ...
for (int j = right; j >= left; j--) { // right to left along the bottom row
out.add(a[bottom][j]);
}
bottom--;
}
if (left <= right) { // ... and so may a column
for (int i = bottom; i >= top; i--) { // bottom to top up the left column
out.add(a[i][left]);
}
left++;
}
}
return out;
}
The two if checks are the important part. After the top row and right column are done, a single row or column may be all that remains, and without the checks it would be walked a second time. The dry run below (output/04-spiral-trace.txt) shows round 2 skipping its bottom row:
[ 1 2 3 4]
[ 5 6 7 8]
[ 9 10 11 12]
round 1: top=0 bottom=2 left=0 right=3
top row, left to right -> [1, 2, 3, 4]
right column, top to bottom -> [8, 12]
bottom row, right to left -> [11, 10, 9]
left column, bottom to top -> [5]
round 2: top=1 bottom=1 left=1 right=2
top row, left to right -> [6, 7]
right column, top to bottom -> []
bottom row skipped (top > bottom)
left column, bottom to top -> []
spiralOrder = [1, 2, 3, 4, 8, 12, 11, 10, 9, 5, 6, 7]
The fingerprint of missing checks: the spiral of the single row [[1, 2, 3]] comes out as [1, 2, 3, 2, 1], with numbers repeated. It is reproduced in the mistakes section.
Going deeper: the reverse problem and edge shapes
The reverse exercise — fill an n x n matrix with 1 to n×n in spiral order — uses the same four boundaries with an assignment instead of a read (Spiral.spiralMatrix in Spiral.java). Single rows, single columns and a single cell all work unchanged (output/04a-spiral-results.txt):
The spiral visits every cell exactly once, so the work is rows × columns. The repository checks that the result is a permutation of the input on 2,000 random shapes (output/07-random-agreement.txt).
Rotating by 90 degrees: transpose, then reverse each row
Rotation looks like the hardest of the five, until you notice that a clockwise quarter turn is two easy steps you already have. Transpose the matrix, then reverse every row.
Follow the blue top row in the diagram: it becomes the left column after the transpose and the right column after the reversal, which is where a clockwise turn sends it. Rotating into a new matrix needs only the destination formula, and it works for rectangular input too, because the result simply has swapped dimensions (Rotation.java):
public static int[][] rotateClockwise(int[][] a) {
MatrixBasics.requireRectangular(a);
int rows = a.length, cols = a[0].length;
int[][] r = new int[cols][rows];
for (int i = 0; i < rows; i++) {
for (int j = 0; j < cols; j++) {
r[j][rows - 1 - i] = a[i][j];
}
}
return r;
}
The in-place version for a square matrix is just the two steps (Rotation.java):
public static void rotateClockwiseInPlace(int[][] a) {
Transpose.transposeInPlace(a);
for (int[] row : a) {
for (int left = 0, right = row.length - 1; left < right; left++, right--) {
int tmp = row[left];
row[left] = row[right];
row[right] = tmp;
}
}
}
Real output for a 3×3 matrix, including a 2×3 rotation that must create a new 3×2 matrix (output/05-rotation.txt):
Going deeper: the four-cell layer swap, other angles
Interviewers often ask for the one-pass version: work ring by ring, and move four cells one quarter turn around the ring at a time. The loop runs to i < last because the corner at last already belongs to the next side.
public static void rotateClockwiseLayers(int[][] a) {
MatrixBasics.requireRectangular(a);
if (a.length != a[0].length) {
throw new IllegalArgumentException("in-place rotation needs a square matrix but got " + MatrixBasics.shape(a));
}
int n = a.length;
for (int layer = 0; layer < n / 2; layer++) {
int first = layer, last = n - 1 - layer;
for (int i = first; i < last; i++) { // i < last: the corner at 'last' belongs to the next side
int offset = i - first;
int top = a[first][i];
a[first][i] = a[last - offset][first]; // left -> top
a[last - offset][first] = a[last][last - offset]; // bottom -> left
a[last][last - offset] = a[i][last]; // right -> bottom
a[i][last] = top; // top -> right
}
}
}
[1 2 3]
[4 5 6]
[7 8 9]
layer 0, i=0: left 7 -> top, bottom 9 -> left, right 3 -> bottom, top 1 -> right
[7 2 1]
[4 5 6]
[9 8 3]
layer 0, i=1: left 4 -> top, bottom 8 -> left, right 6 -> bottom, top 2 -> right
[7 4 1]
[8 5 2]
[9 6 3]
Counter-clockwise and 180-degree rotations are one-line formula changes: rotateCounterClockwise and rotate180 in Rotation.java, with their output in output/05-rotation.txt. The repository checks that all three clockwise methods agree, and that four turns return the original, on 2,000 random matrices (output/07-random-agreement.txt).
1. in-place transpose with the inner loop starting at j = 0 instead of j = i + 1
input
[1 2 3]
[4 5 6]
[7 8 9]
result (identical to the input, every pair was swapped twice)
[1 2 3]
[4 5 6]
[7 8 9]
2. product result allocated as rows(A) x rows(A) instead of rows(A) x cols(B)
2x3 times 3x4, correct result shape 2x4
wrong version -> ArrayIndexOutOfBoundsException: Index 2 out of bounds for length 2
3. spiral without the 'is there still a row / column left?' checks
input [[1, 2, 3]] (a single row)
wrong = [1, 2, 3, 2, 1]
correct = [1, 2, 3]
4. layer rotation with i <= last instead of i < last (the corner is moved twice)
input
[1 2 3]
[4 5 6]
[7 8 9]
wrong
[9 4 7]
[8 5 2]
[3 6 1]
correct
[7 4 1]
[8 5 2]
[9 6 3]
5. 'copy' made with clone() is shallow
original = [[1, 2], [3, 4]]; copy = original.clone(); copy[0][0] = 99
original[0][0] is now 99 (the rows are shared)
copyOf() makes new rows: changing deep[1][1] left original[1][1] at 4
6. int overflow in the dot product
[[50000]] * [[50000]] with plain multiply = -1794967296 (true value 2500000000)
multiplyExact -> ArithmeticException: integer overflow
Two rules fix most of these: size the result of a product as rows(A) x cols(B), and use a wider type or Math.multiplyExact when the values can be large.
How much work is it? Counting, not timing
Examiners ask for the complexity of each program, so the repository counts instead of timing: Complexity.java runs the same loops with a counter added, and the tests assert the counts. Timings from a shared machine would drift between runs; counts never do.
multiplications for an n x n product (i-j-k loop)
n = 10 1,000 multiplications
n = 100 1,000,000 multiplications
n = 200 8,000,000 multiplications
doubling n from 100 to 200 multiplies the work by 8
2x3 times 3x2: 12 multiplications (m * n * p = 2 * 3 * 2)
in-place transpose swaps, n x n
n = 3 3 swaps (n * (n - 1) / 2 = 3)
n = 100 4,950 swaps (n * (n - 1) / 2 = 4,950)
layer rotation four-cell moves, n x n
n = 3 2 moves (n * n / 4 rounded down = 2)
n = 4 4 moves (n * n / 4 rounded down = 4)
n = 100 2,500 moves (n * n / 4 rounded down = 2,500)
spiral: cells visited vs rows * cols
1 x 1 visits = 1 rows * cols = 1
1 x 7 visits = 7 rows * cols = 7
7 x 1 visits = 7 rows * cols = 7
3 x 4 visits = 12 rows * cols = 12
5 x 5 visits = 25 rows * cols = 25
40 x 25 visits = 1,000 rows * cols = 1,000
The line to remember is the doubling: going from n = 100 to n = 200 multiplies the work of a product by 8, not 2.
Going deeper: how the repository proves the programs agree
Ten JUnit tests write every transcript on this page while asserting the same numbers, so a figure in the post fails the build the moment it stops being true. Nine algebraic laws are also checked on seeded random matrices (output/07-random-agreement.txt):
rotateClockwise == transpose-then-reverse == layer swaps (n x n, n = 1..8): 2000 agree, 0 disagree
four clockwise turns return the original: 2000 agree, 0 disagree
clockwise then counter-clockwise returns the original: 2000 agree, 0 disagree
transpose twice returns the original (random m x n): 2000 agree, 0 disagree
(A * B) transposed == B transposed * A transposed: 2000 agree, 0 disagree
A * I == A and I * A == A: 2000 agree, 0 disagree
i-j-k product == i-k-j product: 2000 agree, 0 disagree
A * (B + C) == A * B + A * C: 2000 agree, 0 disagree
spiral order is a permutation of all m * n elements: 2000 agree, 0 disagree
Run it yourself: ./scripts/run-all.sh in the module regenerates every file in output/.
Why can a 2×3 matrix not be transposed in place? Its transpose is 3×2, a different shape, so a new array is required (03-transpose.txt).
What is the time complexity of matrix multiplication? O(m × n × p), which is O(n3) for square matrices: 1,000,000 multiplications at n = 100 (08-operation-counts.txt).
How do you rotate a square matrix in place? Transpose, then reverse each row, or swap four cells per step ring by ring (05-rotation.txt, 06-layer-rotation-trace.txt).
Is A × B equal to B × A? Not in general, and often only one product exists at all (the shape rule above).
Why does clone() not copy a 2D array? It copies only the outer array; the rows are shared (09-pitfalls.txt, mistake 5).
What happens to the spiral of a single row? Correct code returns it unchanged; code without the boundary checks repeats elements (09-pitfalls.txt, mistake 3).
Should you write this by hand outside a lab? No. These programs are the right size for learning loops, indexing and complexity, and for interviews. For real numeric work on large matrices use a maintained numerical library such as Apache Commons Math or EJML rather than a hand-rolled int[][]: they handle element types, in-place operations and numerical care that this post deliberately leaves out.
No Comments yet!