Multidimensional Array Example in Java
On this page (10sections)
Introduction
Multidimensional array is a classic Java console program that demonstrates the concept with complete source code and sample output. Arrays store fixed-size sequences with fast index access — a foundation before collections.
This tutorial walks through the program line by line, explains how the logic works, and highlights best practices you can apply in your own code.
Definition
An array is a data structure consisting of a collection of elements (values or variables), each identified by at least one array index or key. An array is stored so that the position of each element can be computed from its index by a mathematical formula. The simplest type of data structure is a linear array, also called one-dimensional array. Multi dimensional arrays are nothing but arrays of arrays. You can create arrays of two or more dimensions. For a two-dimensional array, the element with indices i,j would have address B + c i + d j, where the coefficients c and d are the row and column address increments, respectively.
Syntax
Data_type Variable_name[][] = new Data_type[Length][Length];
Multidimensional array Example Program
class TwoDimensionalArray{
public static void main(String args[]) {
int twoDimenArray[][]= new int[3][5];
int i, j, k = 0;
for(i=0; i<3; i++)
for(j=0; j<5; j++){
twoDimenArray[i][j] = k;
k++;
}
for(i=0; i<3; i++){
for(j=0; j<5; j++){
System.out.print(twoDimenArray[i][j] + " ");
}
System.out.println();
}
}
}
Sample Output
0 1 2 3 4
5 6 7 8 9
10 11 12 13 14
When to use
Use this multidimensional array example when learning or revising core Java syntax.
How it works
-
Execution begins in the
mainmethod — the JVM calls this method when you run the class. -
int twoDimenArray[][]= new int[3][5];updates a variable used in the calculation or output. -
int i, j, k = 0;updates a variable used in the calculation or output. -
A loop repeats the block until its condition becomes false.
-
A loop repeats the block until its condition becomes false.
-
twoDimenArray[i][j] = k;updates a variable used in the calculation or output. -
A loop repeats the block until its condition becomes false.
-
A loop repeats the block until its condition becomes false.
Best Practices
- Use meaningful variable and class names that describe their purpose.
- Compile and run the program locally — modify values to see how output changes.
- Read compiler errors carefully; they usually point to the exact line to fix.
Common Mistakes
- Copying code without understanding each line — practice by changing one statement at a time.
- Mismatching the public class name and the
.javafilename. - Forgetting semicolons at the end of statements.