For working professionals
For fresh graduates
More
6. JDK in Java
7. C++ Vs Java
16. Java If-else
18. Loops in Java
20. For Loop in Java
46. Packages in Java
53. Java Collection
56. Generics In Java
57. Java Interfaces
60. Streams in Java
63. Thread in Java
67. Deadlock in Java
74. Applet in Java
75. Java Swing
76. Java Frameworks
78. JUnit Testing
81. Jar file in Java
82. Java Clean Code
86. Java 8 features
87. String in Java
93. HashMap in Java
98. Enum in Java
101. Hashcode in Java
105. Linked List in Java
109. Array Length in Java
111. Split in java
112. Map In Java
115. HashSet in Java
118. DateFormat in Java
121. Java List Size
122. Java APIs
128. Identifiers in Java
130. Set in Java
132. Try Catch in Java
133. Bubble Sort in Java
135. Queue in Java
142. Jagged Array in Java
144. Java String Format
145. Replace in Java
146. charAt() in Java
147. CompareTo in Java
151. parseInt in Java
153. Abstraction in Java
154. String Input in Java
156. instanceof in Java
157. Math Floor in Java
158. Selection Sort Java
159. int to char in Java
164. Deque in Java
172. Trim in Java
173. RxJava
174. Recursion in Java
175. HashSet Java
177. Square Root in Java
190. Javafx
How do you store tabular data like matrices or grids in Java using a simple, structured format?
That’s where the two-dimensional array in Java comes in. A 2D array is essentially an array of arrays, allowing you to organize data in rows and columns. It’s commonly used in mathematical operations, game boards, and any scenario that requires grid-based storage.
In this tutorial, you’ll learn the syntax of two-dimensional arrays in Java, how to create them, and how to use them with both primitive data types and objects. We’ll also walk through accessing elements with row-column indexing, and provide a full example program using a 2D array in Java. Whether you’re new to arrays or looking to deepen your understanding, this guide will help you apply 2D arrays effectively in real projects.
Want to build strong Java foundations for job-ready development? Check out upGrad’s Software Engineering Courses to master Java, data structures, and real-world problem-solving.
In Java, you can declare a two-dimensional array by specifying the data type, followed by the array name and the size of each dimension within square brackets.
The syntax for declaring a two-dimensional array in Java is as follows:
dataType[][] arrayName = new dataType[rows][columns];
Let us now break down the syntax to understand how we can declare a 2D array.
Here is the syntax for assigning values after declaring the 2D array:
arrayName[rowIndex][columnIndex] = value;
In the above syntax, rowIndex represents the index of the row, columnIndex represents the index of the column, and value represents the element you want to assign or retrieve. Indices start from 0, so the valid index values for rows and columns range from 0 to (number of rows/columns - 1).
Let us now create a two-dimensional integer array called matrix with three 3 rows and four columns:
int[][] matrix = new int[3][4];
For assigning a value to any specific element in an array, we use the following syntax:
matrix[rowIndex][columnIndex] = value;
For retrieving the value stored at a specific element, we can use the following syntax:
int element = matrix[rowIndex][columnIndex];
Here is a Java program that creates and initializes a two-dimensional array:
public class upGradTutorials {
public static void main(String[] args) {
// Create a 2D array with 3 rows and 4 columns
int[][] matrix = new int[3][4];
// Initialize the elements of the array
matrix[0][0] = 1;
matrix[0][1] = 2;
matrix[0][2] = 3;
matrix[0][3] = 4;
matrix[1][0] = 5;
matrix[1][1] = 6;
matrix[1][2] = 7;
matrix[1][3] = 8;
matrix[2][0] = 9;
matrix[2][1] = 10;
matrix[2][2] = 11;
matrix[2][3] = 12;
// Print the elements of the array
for (int i = 0; i < matrix.length; i++) {
for (int j = 0; j < matrix[i].length; j++) {
System.out.print(matrix[i][j] + " ");
}
System.out.println(); // Move to the next line after each row
}
}
}
In this example, we create a two-dimensional array called a matrix with three rows and four columns using the statement int[][] matrix = new int[3][4];. After that, we initialize the elements of the array by assigning values to each element using the array indices.
Remember that arrays in Java are zero-based, meaning the indices start from 0. In the matrix array, the row indices range from 0 to 2 (3 rows), and the column indices range from 0 to 3 (4 columns).
We can access and modify the elements of the array using the same indexing syntax. For example, matrix[1][2] represents the element in the second row and third column.
Once the array is created and initialized, we can perform various operations, such as reading and updating its elements, performing calculations, or iterating over the array using loops to process its contents.
Here is an example of creating and initializing a two-dimensional array of a primitive type (int) in Java:
public class upGradTutorials {
public static void main(String[] args) {
// Create a 2D array of integers with 3 rows and 4 columns
int[][] matrix = {
{1, 2, 3, 4},
{5, 6, 7, 8},
{9, 10, 11, 12}
};
// Access and print the elements of the array
for (int i = 0; i < matrix.length; i++) {
for (int j = 0; j < matrix[i].length; j++) {
System.out.print(matrix[i][j] + " ");
}
System.out.println(); // Move to the next line after each row
}
}
}
In the above program, we declare and initialize a two-dimensional array of integers named matrix. We use curly braces to define the elements of the array directly within the declaration. The outer curly braces represent the rows, and the inner curly braces represent the elements in each row.
The elements of the array are accessed and printed using nested loops. The outer loop is used for iterating over the rows (matrix.length gives the number of rows), and the inner loop is used for iterating over the columns (matrix[i].length gives the number of columns in each row).
You can modify the size of the array, as well as the values of the elements, to suit your requirements. The same approach can be used for other primitive types like double, char, boolean, etc., by replacing the data type in the declaration and initialization of the array.
Here is an example of creating and initializing a two-dimensional array of objects in Java:
public class upGradTutorials {
public static void main(String[] args) {
// Create a 2D array of Person objects with 2 rows and 3 columns
Person[][] people = new Person[2][3];
// Initialize the elements of the array
people[0][0] = new Person("Alice", 25);
people[0][1] = new Person("Bob", 30);
people[0][2] = new Person("Charlie", 35);
people[1][0] = new Person("David", 40);
people[1][1] = new Person("Eve", 45);
people[1][2] = new Person("Frank", 50);
// Access and print the elements of the array
for (int i = 0; i < people.length; i++) {
for (int j = 0; j < people[i].length; j++) {
System.out.println(people[i][j].getName() + " - " + people[i][j].getAge());
}
}
}
}
class Person {
private String name;
private int age;
public Person(String name, int age) {
this.name = name;
this.age = age;
}
public String getName() {
return name;
}
public int getAge() {
return age;
}
}
In this example, we define a class Person to represent individuals with a name and age. We then create a two-dimensional array people of Person objects with two rows and three columns.
To initialize the elements of the array, we assign new Person objects to each element using the array indices. For example, people[0][0] = new Person("Alice", 25); creates a new Person object with the name "Alice" and age 25, and assigns it to the element at the first row and first column.
We can then access the elements of the array using nested loops and perform operations on the Person objects. In this case, we print the name and age of each Person object. You can modify the array size, add more properties to the Person class, and customize the initialization of the array elements to suit your needs.
In the above sections, we have covered how to use syntax to create and declare two-dimensional arrays in Java. Let us check out a working
public class upGradTutorials {
public static void main(String[] args) {
// Declare and initialize a 3x3 two-dimensional array
int[][] matrix = {{1, 2, 3}, {4, 5, 6}, {7, 8, 9}};
// Access and print the elements of the array
System.out.println("Elements of the matrix:");
for (int i = 0; i < matrix.length; i++) {
for (int j = 0; j < matrix[i].length; j++) {
System.out.print(matrix[i][j] + " ");
}
System.out.println(); // Move to the next line after each row
}
}
}
In the above program, we declare and initialize a 3x3 two-dimensional array called matrix. Then, we use nested loops to iterate over the array and print its elements row by row. The outer loop is used for iterating over the rows (matrix.length gives the number of rows), and the inner loop is used for iterating over the columns (matrix[i].length gives the number of columns in each row).
The output displays the elements of the matrix in a row-by-row format. Each row is printed on a new line, with the elements separated by spaces. We can modify the array size and the values to suit our needs and perform various operations using the two-dimensional array based on our program requirements.
Here is another two-dimensional array in Java program example that will help you understand the concept of two-dimensional programs better:
public class upGradTutorials {
public static void main(String[] args) {
// Declare and initialize an array of integers
int[] numbers = {5, 10, 15, 20, 25};
// Access and print the elements of the array
System.out.println("Elements of the array:");
for (int i = 0; i < numbers.length; i++) {
System.out.println(numbers[i]);
}
// Update an element of the array
numbers[2] = 30;
// Access and print the updated element
System.out.println("Updated element: " + numbers[2]);
// Calculate and print the sum of all elements
int sum = 0;
for (int i = 0; i < numbers.length; i++) {
sum += numbers[i];
}
System.out.println("Sum of all elements: " + sum);
}
}
In this example, we declare and initialize an array of integers called numbers with five elements. We then use a loop to access and print each array element.
Next, we update the element's value at index 2 to 30. We access and print the updated element to verify the change. Lastly, we calculate the sum of all elements in the array using a loop and print the result.
In conclusion, having a solid understanding of the two-dimensional array in Java is crucial for managing data in a structured manner. It facilitates the manipulation and representation of data in rows and columns, enabling the development of more intricate programs.
To enhance your expertise in Java programming, it would be beneficial to consider enrolling in a suitable course offered by upGrad. A well-rounded curriculum and expert instructors can provide the guidance to excel in Java and effectively manipulate arrays, empowering you on your programming path.
A two-dimensional array in Java is an array of arrays that stores data in rows and columns. It’s ideal for representing matrices, tables, and grid-like structures in both programming logic and data storage.
You can declare a 2D array in Java using syntax like int[][] matrix;
. This sets up a reference for a two-dimensional array where data can be stored in a row-column format.
To create a two-dimensional array in Java, use int[][] arr = new int[3][4];
for a 3-row, 4-column structure. You can also initialize values directly using nested curly braces.
The basic syntax of a 2D array in Java is datatype[][] arrayName = new datatype[rows][columns];
. This applies to both primitive and object-based arrays.
Yes, you can create a two-dimensional array of objects in Java like Student[][] data = new Student[3][2];
. Each cell can hold an instance of a class.
To access elements in a two-dimensional array in Java, use array[i][j]
, where i
is the row index and j
is the column index. Indexing starts from 0.
2D arrays in Java are widely used in mathematical operations (like matrix multiplication), game development (like tic-tac-toe), and table-based data storage and manipulation.
You can create a 2D array in Java with values like:int[][] grid = { {1, 2}, {3, 4}, {5, 6} };
. This is useful when the data is known beforehand.
No, in Java, a two-dimensional array is essentially an array of arrays. Each row itself is a one-dimensional array, which allows flexibility in row size if needed.
Yes, you can use nested for
loops to iterate over each cell of a 2D array in Java. This is useful for reading inputs or applying logic across the grid.
A basic 2D array program in Java creates an array, assigns values, and prints them using nested loops. It’s a foundational exercise in understanding array structures and indexing.
Take the Free Quiz on Java
Answer quick questions and assess your Java knowledge
Author|900 articles published
Talk to our experts. We are available 7 days a week, 9 AM to 12 AM (midnight)
Indian Nationals
1800 210 2020
Foreign Nationals
+918068792934
1.The above statistics depend on various factors and individual results may vary. Past performance is no guarantee of future results.
2.The student assumes full responsibility for all expenses associated with visas, travel, & related costs. upGrad does not provide any a.