Tutorial

Matrix Programs in Java

Published on August 3, 2022
author

Pankaj

Matrix Programs in Java

A Matrix is a rectangular array. The elements are arranged in the rows and columns. In this tutorial, we will look at some matrix programs in Java.

Graphical Representation of Matrix

Matrix
Matrix

Matrix in Java

We can implement a matrix using two dimensional array in Java. The element at row “r” and column “c” can be accessed using index “array[r][c]”.

Matrix Programs in Java

Since we are using two-dimensional arrays to create a matrix, we can easily perform various operations on its elements. In this tutorial, we will learn how to create a matrix from user input. Then we will add, subtract, and multiply two matrices and print the result matrix on the console.

1. Adding Two Matrix

Here is the simple program to populate two matrices from the user input. Then add its elements at the corresponding indices to get the addition of the matrices. Finally, we will print the sum of the matrices.

package com.journaldev.examples;

import java.util.Scanner;

public class MatrixPrograms {

	public static void main(String[] args) {
		System.out.println("Please enter the rows in the matrix");
		Scanner sc = new Scanner(System.in);
		int row = sc.nextInt();
		System.out.println("Please enter the columns in the matrix");
		int column = sc.nextInt();

		int[][] first = new int[row][column];
		int[][] second = new int[row][column];

		for (int r = 0; r < row; r++) {
			for (int c = 0; c < column; c++) {
				System.out.println(String.format("Enter first[%d][%d] integer", r, c));
				first[r][c] = sc.nextInt();
			}
		}

		for (int r = 0; r < row; r++) {
			for (int c = 0; c < column; c++) {
				System.out.println(String.format("Enter second[%d][%d] integer", r, c));
				second[r][c] = sc.nextInt();
			}
		}

		// close the scanner
		sc.close();

		// print both matrices
		System.out.println("First Matrix:\n");
		print2dArray(first);

		System.out.println("Second Matrix:\n");
		print2dArray(second);

		// sum of matrices
		sum(first, second);
	}

	// below code doesn't take care of exceptions
	private static void sum(int[][] first, int[][] second) {
		int row = first.length;
		int column = first[0].length;
		int[][] sum = new int[row][column];

		for (int r = 0; r < row; r++) {
			for (int c = 0; c < column; c++) {
				sum[r][c] = first[r][c] + second[r][c];
			}
		}

		System.out.println("\nSum of Matrices:\n");
		print2dArray(sum);
	}

	private static void print2dArray(int[][] matrix) {
		for (int r = 0; r < matrix.length; r++) {
			for (int c = 0; c < matrix[0].length; c++) {
				System.out.print(matrix[r][c] + "\t");
			}
			System.out.println();
		}
	}
}
Matrix programs in Java
Adding Two Matrices

2. Subtracting Two Matrices

Here is the function to subtraction second matrix elements from the first matrix and then print the result matrix.

private static void subtract(int[][] first, int[][] second) {
	int row = first.length;
	int column = first[0].length;
	int[][] sum = new int[row][column];

	for (int r = 0; r < row; r++) {
		for (int c = 0; c < column; c++) {
			sum[r][c] = first[r][c] - second[r][c];
		}
	}

	System.out.println("\nSubtraction of Matrices:\n");
	print2dArray(sum);
}

3. Multiplying Two Matrices

Below method will multiply the matrix elements and print the result matrix.

private static void multiply(int[][] first, int[][] second) {
	int row = first.length;
	int column = first[0].length;
	int[][] sum = new int[row][column];

	for (int r = 0; r < row; r++) {
		for (int c = 0; c < column; c++) {
			sum[r][c] = first[r][c] * second[r][c];
		}
	}

	System.out.println("\nMultiplication of Matrices:\n");
	print2dArray(sum);
}

Reference: Wikipedia

Thanks for learning with the DigitalOcean Community. Check out our offerings for compute, storage, networking, and managed databases.

Learn more about our products

About the authors
Default avatar
Pankaj

author

While we believe that this content benefits our community, we have not yet thoroughly reviewed it. If you have any suggestions for improvements, please let us know by clicking the “report an issue“ button at the bottom of the tutorial.

Still looking for an answer?

Ask a questionSearch for more help

Was this helpful?
 
JournalDev
DigitalOcean Employee
DigitalOcean Employee badge
January 30, 2021

can you take input for rows and column without nested loop

- Shivam patel

    JournalDev
    DigitalOcean Employee
    DigitalOcean Employee badge
    August 14, 2019

    Hi Pankaj, I just visited your website and the posts look really great. I want to ask you one question about how you are writing the codes in the blackboard and again we can copy the codes also. Can you please let me know how to do this if I want to write some code like you are writing and publishing. Thank you.

    - Biswaranjan Mishra

      Try DigitalOcean for free

      Click below to sign up and get $200 of credit to try our products over 60 days!

      Sign up

      Join the Tech Talk
      Success! Thank you! Please check your email for further details.

      Please complete your information!

      Become a contributor for community

      Get paid to write technical tutorials and select a tech-focused charity to receive a matching donation.

      DigitalOcean Documentation

      Full documentation for every DigitalOcean product.

      Resources for startups and SMBs

      The Wave has everything you need to know about building a business, from raising funding to marketing your product.

      Get our newsletter

      Stay up to date by signing up for DigitalOcean’s Infrastructure as a Newsletter.

      New accounts only. By submitting your email you agree to our Privacy Policy

      The developer cloud

      Scale up as you grow — whether you're running one virtual machine or ten thousand.

      Get started for free

      Sign up and get $200 in credit for your first 60 days with DigitalOcean.*

      *This promotional offer applies to new accounts only.