Core Java Tutorial

Define Java

C vs C++ vs Java

Java Virtual Machine

Java First Program

Java Data Types

Java Tokens

Java Keywords

Java Operators

Operator Precedence

Java Type Casting

Java Statement

Java If statement

Java Switch statement

Java Loops

Java Jumping Statement

Java Arrays 1D

Java Arrays 2D

Java Variable Size Array

Java Vector

Java Math Methods

Java String Methods

Java String Buffer

User-Defined Method

Java Method Overloading

Java Class & Object

Java Constructor

Java Inheritance

Java Interface

Java Packages

Java Multi-threading

Exceptional Handling

File Handling

Java Applets

Java DataBase Connectivity

Page Stats

Visitor: 300

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: WAP 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: WAP to initialize the matrix.

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