VOOZH about

URL: https://mkyong.com/java/java-two-dimensional-array-example/

⇱ Java two-dimensional array example - Mkyong.com


Skip to content

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

mkyong

Founder of Mkyong.com, passionate Java and open-source technologies. If you enjoy my tutorials, consider making a donation to these charities.

0 Comments
Most Voted
Newest Oldest
Inline Feedbacks
View all comments