Skip to content

TwoDimensionalArrays

Zhamri Che Ani edited this page Dec 23, 2024 · 3 revisions

Common Use Cases

  1. Matrix Representation: Useful in representing grids, matrices, or tables.
  2. Game Boards: For board games like chess and tic-tac-toe.
  3. Image Processing: Represent pixel values of an image.

Declaration

int[][] zhamriArray;

Initialization

With size:

zhamriArray = new int[3][4]; // 3 rows and 4 columns

With values:

int[][] zhamriArray = {
    {1, 2, 3},
    {4, 5, 6},
    {7, 8, 9}
};

OR

int[][] zhamriArray = new int[][]{
        {1, 2, 3},
        {4, 5, 6},
        {7, 8, 9}
};

Accessing an element

int value = zhamriArray[1][2]; // Gets the element in 2nd row and 3rd column

Modify an element

zhamriArray[0][0] = 10; // Sets the element in the 1st row and 1st column to 10

Length Property

  • zhamriArray.length gives the number of rows.
  • zhamriArray[rowIndex].length gives the number of columns in a specific row.

Iterating using Nested Loops

for (int i = 0; i < zhamriArray.length; i++) { // Rows
    for (int j = 0; j < zhamriArray[i].length; j++) { // Columns
        System.out.print(zhamriArray[i][j] + " ");
    }
    System.out.println();
}

Iterating using Enhanced For Loop

for (int[] row : zhamriArray) {
    for (int val : row) {
        System.out.print(val + " ");
    }
    System.out.println();
}

Example Code-1

public class TwoDArrayExample {
    public static void main(String[] args) {
        int[][] zhamriArray = {
            {1, 2, 3},
            {4, 5, 6},
            {7, 8, 9}
        };

        // Print the 2D array
        for (int i = 0; i < zhamriArray.length; i++) {
            for (int j = 0; j < zhamriArray[i].length; j++) {
                System.out.print(zhamriArray[i][j] + " ");
            }
            System.out.println();
        }
    }
}

Output

1 2 3
4 5 6
7 8 9

Example Code-2

public class Test2D {

    private static int[][] zhamriArray;

    public static void main(String[] args) {
        myInput();
        zhamriArray[2][1] = arrayAddition(zhamriArray[1][2], zhamriArray[2][2]);
        myOutput();
    }

    public static void myInput() {
        zhamriArray = new int[][]{
                {1, 2, 3, 100},
                {4, 5, 6, 100},
                {7, 8, 9, 100}
        };
    }

    public static int arrayAddition(int a, int b) {  // a = 6, b = 9
        int result = a + b;
        return result;
    }

    public static void myOutput() {
        for (int i = 0; i < zhamriArray.length; i++) {
            for (int j = 0; j < zhamriArray[i].length; j++) {
                System.out.print(zhamriArray[i][j] + " ");
            }
            System.out.println();
        }
    }
}

Output

1 2 3 100 
4 5 6 100 
7 15 9 100 

Multidimensional Arrays

Java supports arrays with more than two dimensions, e.g., 3D arrays, but they are rarely used due to increased complexity.

Example

int[][][] zhamriArray;