Ad

Java Double-Dimensional Arrays or 2d-Arrays

2D Array

Double-Dimensional Arrays or 2d-Arrays are the combination of rows and columns. Normally, a 2D-Array is use to represent data in the form of matrix.

Syntax to declare 2d-Arrays:

int a[][] = new int [3][4];
or
int a[][];
a = new int [3][4];

In the above syntax, 1st square bracket represents number of rows and 2nd square bracket represent number of columns. The above declaration tells the compiler that we are declaring 3 rows and 4 columns. 'new' keyword is used to allocate memory at run time.

Example 1: Write a program in Java to Input 3x3 matrix and print it.

package arrays2d;
import java.util.Scanner;
public class Arrays2d {
   public static void main(String[] args) {
        int i, j, a[][] = new int [3][3];
        Scanner scan = new Scanner(System.in);
        System.out.println("Enter 3x3 matrix");
        for(i=0;i<=2;i++)
        {
            for(j=0;j<=2;j++)
            {
                a[i][j] = scan.nextInt();
            }
        }
        System.out.println("3x3 matrix is:\n");
        for(i=0;i<=2;i++)
        {
            for(j=0;j<=2;j++)
            {
                System.out.print("  "+a[i][j]);
            }
            System.out.println("\n");
        }
    }
}
Enter 3x3 matrix 1 2 3 4 5 6 7 8 9
3x3 matrix is:
1 2 3
4 5 6
7 8 9

2D-Arrays can be initialize as follows:

int a[2][3] = { 0, 1, 2, 3, 4, 5 } ;
int a[][] = { { 1, 2, 3 }, { 4, 5, 6 } };

Example 2: Write a Java program to initialize the matrix and print it.

package Arrays2d;
public class Arrays2d {
    public static void main(String[] args) {
        int a[][] = {{10,20,30}, {40,50,60}, {70,80,90} };
        int i, j;
        System.out.println("3x3 Matrix is:");
        for(i=0;i<=2;i++)
        {
            for(j=0;j<=2;j++)
            {
                System.out.print("  "+a[i][j]);
            }
            System.out.println("\n");
        }
    }
}
3x3 Matrix is
10 20 30
40 50 60
70 80 90