Skip to content
Related Articles

Related Articles

Improve Article
How to read a Matrix from user in Java?
  • Last Updated : 05 Mar, 2019

Given task is to read a matrix from the user. The size and number of elements of matrices are to be read from the keyboard.

// Java program to read a matrix from user
import java.util.Scanner;
public class MatrixFromUser {
    // Function to read matrix
    public static void readMatrixByUser()
        int m, n, i, j;
        Scanner in = null;
        try {
            in = new Scanner(;
            System.out.println("Enter the number "
                               + "of rows of the matrix");
            m = in.nextInt();
            System.out.println("Enter the number "
                               + "of columns of the matrix");
            n = in.nextInt();
            // Declare the matrix
            int first[][] = new int[m][n];
            // Read the matrix values
            System.out.println("Enter the elements of the matrix");
            for (i = 0; i < m; i++)
                for (j = 0; j < n; j++)
                    first[i][j] = in.nextInt();
            // Display the elements of the matrix
            System.out.println("Elements of the matrix are");
            for (i = 0; i < m; i++) {
                for (j = 0; j < n; j++)
                    System.out.print(first[i][j] + "  ");
        catch (Exception e) {
        finally {
    // Driver code
    public static void main(String[] args)
Enter the number of rows of the matrix 2
Enter the number of columns of the matrix 2
Enter the elements of the matrix
Elements of the matrix are
1 2 
3 4 

Attention reader! Don’t stop learning now. Get hold of all the important Java Foundation and Collections concepts with the Fundamentals of Java and Java Collections Course at a student-friendly price and become industry ready. To complete your preparation from learning a language to DS Algo and many more,  please refer Complete Interview Preparation Course.

My Personal Notes arrow_drop_up
Recommended Articles
Page :