View All
View All
View All
View All
View All
View All
View All
View All
View All
View All
View All
View All
View All
View All
View All
View All
View All
View All
View All
View All
View All
View All
View All
View All
View All
View All

Two-Dimensional Array in Java: Syntax, Creation & Examples

Updated on 24/06/202512,259 Views

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.

Two-Dimensional Array in Java Syntax

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.

  • dataType: It represents the data type of the array's elements. For example, int, double, String, etc.
  • arrayName: It is the name you choose for your array variable.
  • rows: It specifies the number of rows in the array. This is the first dimension of the array.
  • columns: It specifies the number of columns in the array. This is the second dimension of the 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];

Create a Two-Dimensional Array in Java

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.

Two-Dimensional Array of Primitive Type in Java

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.

Two-Dimensional Array of Objects in Java

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.

Accessing Two-Dimensional Array Elements in Java

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.

Two-Dimensional Array in Java Example Program

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.

Conclusion

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.

FAQs

1. What is a two-dimensional array in Java?

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.

2. How to declare a 2D array in Java?

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.

3. How do you create and initialize a two-dimensional array in Java?

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.

4. What is the syntax of two-dimensional arrays in Java?

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.

5. Can you store objects in a two-dimensional array in Java?

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.

6. How to access elements in a 2D array in Java?

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.

7. What is a common use case for 2D arrays in Java?

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.

8. How to create a 2D array with predefined values in Java?

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.

9. Is there a difference between 2D arrays and arrays of arrays in Java?

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.

10. Can you use loops to fill a two-dimensional array in Java?

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.

11. What is a simple two-dimensional array program in Java?

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.

image

Take the Free Quiz on Java

Answer quick questions and assess your Java knowledge

right-top-arrow
image
Pavan Vadapalli

Author|900 articles published

Director of Engineering @ upGrad. Motivated to leverage technology to solve problems. Seasoned leader for startups and fast moving orgs. Working on solving problems of scale and long term technology s....

image
Join 10M+ Learners & Transform Your Career
Learn on a personalised AI-powered platform that offers best-in-class content, live sessions & mentorship from leading industry experts.
advertise-arrow

Free Courses

Explore Our Free Software Tutorials

upGrad Learner Support

Talk to our experts. We are available 7 days a week, 9 AM to 12 AM (midnight)

text

Indian Nationals

1800 210 2020

text

Foreign Nationals

+918068792934

Disclaimer

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.