Java two-dimensional array example

A Java 2d array example.

ArrayExample.java

package com.mkyong;

public class ArrayExample {

    public static void main(String[] args) {

        int[][] num2d = new int[2][3];

        num2d[0][0] = 1;
        num2d[0][1] = 2;
        num2d[0][2] = 3;

        num2d[1][0] = 10;
        num2d[1][1] = 20;
        num2d[1][2] = 30;

        //or init 2d array like this :
        int[][] num2dInit = {
                {1, 2, 3},
                {10, 20, 30}
        };

        print2dArray(num2d);

    }

    static void print2dArray(int[][] num2d) {
        // Accessing 2d array with index print
        int index1d, index2d = 0;

        for (int[] num1d : num2d) {
            index1d = 0;
            for (int num : num1d) {
                System.out.println("[" + index2d + "][" + index1d + "] = " + num);
                index1d++;
            }
            index2d++;
        }
    }
}

Output


[0][0] = 1
[0][1] = 2
[0][2] = 3
[1][0] = 10
[1][1] = 20
[1][2] = 30
Note
Read this for more Java array examples

References

About the Author

author image
mkyong
Founder of Mkyong.com, love Java and open source stuff. Follow him on Twitter. If you like my tutorials, consider make a donation to these charities.

Comments

avatar