Java for Beginners · Module 5: Data and Methods
🎯 Tables of Data
Marks of 3 students in 4 subjects, a chessboard, a seating chart, a matrix in mathematics: all of these are tables with rows and columns. A two-dimensional (2D) array stores such a table. You need two indexes to reach one value: the row, then the column.
1️⃣ Creating and Reading a 2D Array
int[][] m = {{1,2,3},{4,5,6}};| col 0 | col 1 | col 2 | |
| row 0 | 1 | 2 | 3 |
| row 1 | 4 | 5 | 6 |
m[1][2] is row 1, column 2: the highlighted 6. m.length = 2 rows, m[0].length = 3 columns.Figure 1: A 2D array is a table of rows and columns.
Program 1: Creating, reading and printing
import java.util.Arrays;
public class TwoD {
public static void main(String[] args) {
int[][] m = {
{1, 2, 3},
{4, 5, 6}
};
System.out.println("rows = " + m.length + ", cols = " + m[0].length);
System.out.println("m[1][2] = " + m[1][2]);
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();
}
int[][] grid = new int[3][4];
grid[2][3] = 9;
System.out.println(Arrays.deepToString(grid));
}
}
rows = 2, cols = 3
m[1][2] = 6
1 2 3
4 5 6
[[0, 0, 0, 0], [0, 0, 0, 0], [0, 0, 0, 9]]
m.lengthis the number of rows.m[0].lengthis the number of columns in row 0.- Reading every element needs a nested loop (Lesson 19): the outer loop picks the row and the inner loop walks along it.
new int[3][4]creates 3 rows of 4 columns, all zeros.Arrays.deepToStringprints a 2D array. (Arrays.toStringwould print only the row addresses.)
2️⃣ An Array of Arrays
m ➜ [0] [1]Figure 2: How a 2D array is really stored.
In Java a 2D array is stored as a main array that holds references to the row arrays. This explains why each row has its own length, and why rows can be different sizes.
3️⃣ Matrix Operations
| Task | Pattern |
| Visit every element | for r ... for c ... using m[r][c] |
| Row count | m.length |
| Column count (row r) | m[r].length |
| Print neatly | Arrays.deepToString(m) |
| Transpose | t[j][i] = a[i][j] |
| Add two matrices | sum[i][j] = a[i][j] + b[i][j] |
Figure 4: Everyday 2D array patterns.
Program 2: Add, multiply and transpose
import java.util.Arrays;
public class MatrixOps {
public static void main(String[] args) {
int[][] a = {{1, 2}, {3, 4}};
int[][] b = {{5, 6}, {7, 8}};
int[][] sum = new int[2][2];
for (int i = 0; i < 2; i++)
for (int j = 0; j < 2; j++)
sum[i][j] = a[i][j] + b[i][j];
System.out.println("A + B = " + Arrays.deepToString(sum));
int[][] prod = new int[2][2];
for (int i = 0; i < 2; i++)
for (int j = 0; j < 2; j++)
for (int k = 0; k < 2; k++)
prod[i][j] += a[i][k] * b[k][j];
System.out.println("A x B = " + Arrays.deepToString(prod));
int[][] t = new int[2][2];
for (int i = 0; i < 2; i++)
for (int j = 0; j < 2; j++)
t[j][i] = a[i][j];
System.out.println("A transposed = " + Arrays.deepToString(t));
int total = 0;
for (int[] row : a)
for (int v : row)
total += v;
System.out.println("sum of all elements of A = " + total);
}
}
A + B = [[6, 8], [10, 12]]
A x B = [[19, 22], [43, 50]]
A transposed = [[1, 3], [2, 4]]
sum of all elements of A = 10
- Addition adds the matching positions.
- Multiplication needs three loops. Each result cell is the sum of (row of A) × (column of B): for the top-left cell, 1×5 + 2×7 = 19.
- Transpose swaps rows and columns: the element at row i, column j goes to row j, column i.
- For-each over a 2D array: the outer variable is a whole row (
int[] row), and the inner variable is one value. - When a loop body is one statement, the braces may be left out. Keeping them is safer for beginners.
4️⃣ Jagged and Higher-Dimensional Arrays
Figure 3: A jagged array has rows of different lengths.
import java.util.Arrays;
public class Jagged {
public static void main(String[] args) {
int[][] tri = new int[4][];
for (int r = 0; r < tri.length; r++) {
tri[r] = new int[r + 1];
for (int c = 0; c <= r; c++) {
tri[r][c] = (c == 0 || c == r) ? 1 : tri[r - 1][c - 1] + tri[r - 1][c];
}
}
for (int[] row : tri) {
System.out.println(Arrays.toString(row));
}
System.out.println("row lengths: " + tri[0].length + ", " + tri[1].length + ", " + tri[2].length + ", " + tri[3].length);
int[][][] cube = new int[2][3][4];
System.out.println("3D: " + cube.length + " x " + cube[0].length + " x " + cube[0][0].length);
}
}
[1]
[1, 1]
[1, 2, 1]
[1, 3, 3, 1]
row lengths: 1, 2, 3, 4
3D: 2 x 3 x 4
new int[4][]fixes only the number of rows. Each row is created later with its own length, so row r gets r + 1 columns.- Each Pascal’s triangle entry (except the ends) is the sum of the two above it.
- Three or more dimensions follow the same idea:
new int[2][3][4]is 2 blocks of 3 rows of 4 columns. Beyond 3D they are rarely needed.
5️⃣ Errors Beginners Meet
Row or column out of range
public class Oob2 {
public static void main(String[] args) {
int[][] m = new int[2][3];
m[2][0] = 1;
}
}
Exception in thread “main” java.lang.ArrayIndexOutOfBoundsException: Index 2 out of bounds for length 2
at Oob2.main(Oob2.java:4)
- There are only rows 0 and 1. Check
m.lengthfor rows andm[r].lengthfor columns.
Using a row that was never created
public class Npe {
public static void main(String[] args) {
int[][] m = new int[3][];
m[1][0] = 5;
}
}
Exception in thread “main” java.lang.NullPointerException: Cannot store to int array because “<local1>[1]” is null
at Npe.main(Npe.java:4)
- With
new int[3][], the rows do not exist yet and arenull. Create the row first:m[1] = new int[2];. (The message shows<local1>because the program was compiled without debug names. In an IDE it showsm[1].)
⚠️ Common Mistakes
| Mistake | Problem | Fix |
|---|---|---|
Swapping row and column: m[col][row] | Wrong element or out-of-range error | Row first, then column |
Using m.length for the column count | That is the number of rows | Use m[0].length |
Printing with Arrays.toString(m) | Shows row addresses | Arrays.deepToString(m) |
Using new int[3][] then writing into a row | Row is null | Create each row first |
| Multiplying matrices with the wrong sizes | Columns of A must equal rows of B | Check sizes first |
| Reusing the same loop variable in nested loops | Loops interfere | Use i, j, k |
❓ Frequently Asked Questions
Q1. Can rows of a 2D array have different lengths?
Yes. That is a jagged array. Create each row with its own size.
Q2. Is a 2D array stored in one block like in C?
No. In Java it is an array of row arrays, which may sit in different places in memory.
Q3. How do I read a matrix from the keyboard?
Use a nested loop with Scanner: m[i][j] = sc.nextInt(); (Lesson 10).
Q4. How many dimensions can an array have?
Up to 255 in theory, but 1, 2 and rarely 3 are used in practice.
✅ Key Takeaways
- A 2D array is a table:
m[row][col]. m.length= rows,m[r].length= columns of row r.- Use a nested loop to visit every element, or a nested for-each.
- It is really an array of arrays, so jagged arrays are possible.
- Print with
Arrays.deepToString.
🎓 Practice questions: (1) Store marks of 3 students in 4 subjects and print each student’s total. (2) Print the diagonal of a square matrix. (3) Check whether a matrix is symmetric (equal to its transpose). (4) Print a 2D array in a spiral order. (5) Explain the difference betweenm.lengthandm[0].length.
All 30 lessons in this series (open course page)
Module 1 · Getting Started
- Lesson 1: What is Java? Features and Uses
- Lesson 2: Installing the JDK and Running Your First Program
- Lesson 3: JDK, JRE, JVM and WORA Explained
- Lesson 4: JVM Architecture and JIT Compilation
- Lesson 5: Hello World Program Explained Line by Line
Module 2 · Building Blocks
- Lesson 6: Comments, Identifiers and Keywords
- Lesson 7: Variables and Literals
- Lesson 8: Primitive Data Types in Java
- Lesson 9: Type Conversion and Casting
- Lesson 10: Taking Input with the Scanner Class
- Lesson 11: Escape Characters and Variable Scope in Java
Module 3 · Operators
- Lesson 12: Arithmetic Operators and Increment/Decrement in Java
- Lesson 13: Relational and Logical Operators in Java
- Lesson 14: Bitwise and Shift Operators in Java
- Lesson 15: Assignment, Ternary Operator and Operator Precedence in Java
Module 4 · Control Flow
- Lesson 16: if, if-else and else-if Ladder in Java
- Lesson 17: switch Statement in Java (Classic and Modern)
- Lesson 18: while and do-while Loops in Java
- Lesson 19: for Loop and Nested Loops (Patterns) in Java
- Lesson 20: break, continue and Labelled Loops in Java
Module 5 · Data and Methods
- Lesson 21: Arrays in Java (One-Dimensional)
- Lesson 22: Multidimensional Arrays in Java
- Lesson 23: Strings and the String Pool in Java
- Lesson 24: String Methods and StringBuilder in Java
- Lesson 25: Methods and Method Overloading in Java
- Lesson 26: Recursion Basics in Java
- Lesson 27: ArrayList and Wrapper Classes in Java
- Lesson 28: Exception Handling Basics in Java