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;


public class Main {

    public static void main(String[] args) {
        Scanner sc = new Scanner(;
        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] + " ");


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

Other Posts You May Like
Please leave a comment below if you like this post or found some errors, it will help me to improve my content.


Popular Posts from this Blog

Anti Diagonals - The Coding Shala

Shell Script to find sum, product and average of given numbers - The Coding Shala

LeetCode - Bulb Switcher Solution - The Coding Shala

New Year Chaos Solution - The Coding Shala

Sorting the Sentence LeetCode Solution - The Coding Shala