### How to Take 2D Array Input in Java - The Coding Shala

Home >> Java Programs >> Take 2D Array Input

In this post, we are going to learn how to take 2D array/matrix input in Java.

## How to Take 2D Array Input in Java

Write a Java program to take 2D array input from the user. Here we are going to take only an integer data type array.

As we know, a 2D array has rows and columns so first take the number of rows and columns from user input and then create an array of that size. We are going to use the Scanner class to take the inputs.

Java Program:

```import java.util.Scanner;

/**
* https://www.thecodingshala.com/
*/

public class Main {

public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.println("Enter the number of rows");
int n = sc.nextInt();
System.out.println("Enter the number of columns");
int m = sc.nextInt();

// create n*m size 2d array/matrix
int[][] matrix = new int[n][m];

// take elements as input
System.out.println("Enter the elements");
for (int i=0; i<n; i++) {
for (int j=0; j < m; j++) {
matrix[i][j] = sc.nextInt();
}
}

// print the matrix
System.out.println("2D array is: ");
for (int i=0; i<n; i++) {
for (int j=0; j < m; j++) {
System.out.print(matrix[i][j] + " ");
}
System.out.println();
}
}
}
```

Output:

```Enter the number of rows
3
Enter the number of columns
3
Enter the elements
1
2
3
4
5
6
7
8
9
2D array is:
1 2 3
4 5 6
7 8 9
```

Other Posts You May Like