How to Create Matrix in Java: Syntax and Examples
In Java, you create a matrix using a two-dimensional array declared as
type[][] matrix = new type[rows][columns];. You can then fill or access elements using matrix[row][column] notation.Syntax
To create a matrix in Java, use a two-dimensional array. The syntax is:
type[][] matrix = new type[rows][columns];creates a matrix with specified rows and columns.typeis the data type likeint,double, orString.- You access elements with
matrix[row][column].
java
int[][] matrix = new int[3][4];
Example
This example creates a 3x3 matrix, fills it with values, and prints each element.
java
public class MatrixExample { public static void main(String[] args) { int[][] matrix = new int[3][3]; // Fill the matrix with values for (int i = 0; i < 3; i++) { for (int j = 0; j < 3; j++) { matrix[i][j] = i * 3 + j + 1; } } // Print the matrix for (int i = 0; i < 3; i++) { for (int j = 0; j < 3; j++) { System.out.print(matrix[i][j] + " "); } System.out.println(); } } }
Output
1 2 3
4 5 6
7 8 9
Common Pitfalls
Common mistakes when creating matrices in Java include:
- Forgetting that arrays are zero-indexed, so rows and columns start at 0.
- Mixing up row and column order when accessing elements.
- Assuming all rows have the same length (Java allows jagged arrays).
Example of a common mistake and fix:
java
public class MatrixMistake { public static void main(String[] args) { // Wrong: mixing row and column sizes int[][] matrix = new int[3][3]; // Trying to access out of bounds (wrong) // matrix[3][0] = 10; // This causes ArrayIndexOutOfBoundsException // Correct access within bounds matrix[2][0] = 10; System.out.println(matrix[2][0]); } }
Output
10
Quick Reference
| Concept | Syntax/Example |
|---|---|
| Declare matrix | int[][] matrix = new int[rows][columns]; |
| Access element | matrix[row][column] |
| Fill matrix | Use nested loops to assign values |
| Jagged array | int[][] jagged = new int[3][]; jagged[0] = new int[2]; |
| Print matrix | Nested loops with System.out.print() |
Key Takeaways
Create a matrix in Java using a two-dimensional array with syntax type[][] matrix = new type[rows][columns];
Access and assign elements using matrix[row][column] notation, remembering zero-based indexing.
Use nested loops to fill or print matrix elements efficiently.
Beware of ArrayIndexOutOfBoundsException by staying within declared row and column limits.
Java supports jagged arrays where rows can have different lengths.