February 10, 2026

Matrix Multiplication Java Program

This post shows a Java program to multiply two matrices.

To multiply one matrix with another you need to do a dot product of rows and columns. Let’s see it with an example where you are trying to multiply a 3X3 matrix with a 3X2 matrix.

matrix multiplication Java program

How matrix multiplication happens here using dot product can be explained as follows-

First row of first matrix is multiplied with the first column of second matrix.

s11 = r11Xp11 + r12Xp21 + r13Xp31

Second row of first matrix is multiplied with the second column of second matrix.

s12 = r11Xp12 + r12Xp22 + r13Xp32

Then second row of first matrix is multiplied with the first column of second matrix.

s21 = r21Xp11 + r22Xp21 + r23Xp31

and so on...

Java program for matrix multiplication

In the matrix multiplication Java program, initially user is prompted to enter the matrices. You can also check that the number of columns in the first matrix are equal to the number of rows in the second matrix. Then using these two matrices you can do the multiplication.

import java.util.Scanner;

public class MatrixMultiplication {
  public static void main(String[] args) {
    Scanner in = new Scanner(System.in);
    System.out.print("Enter number of rows and columns in the matrix : ");
    int r1 = in.nextInt();
    int c1 = in.nextInt();
    // First matrix
    int[][] matrix1 = prepareMatrix(r1, c1);
    System.out.print("Enter number of rows and columns in the matrix : ");
    int r2 = in.nextInt();
    int c2 = in.nextInt();
		
    if(c1 != r2){
      in.close();
      throw new IllegalArgumentException("Number of columns in the first matrix should be equal to the number of rows in the second matrix");
    }
    // Second matrix
    int[][] matrix2 = prepareMatrix(r2, c2);
    // multiplied result stored in this matrix
    int multiplyMatrix[][] = new int[r1][c2];
    int sum = 0;
    for(int i = 0; i < r1; i++){
      for(int j = 0; j < c2; j++){                
        for(int k = 0; k < c1; k++){
          sum = sum + matrix1[i][k] * matrix2[k][j];
        }
        multiplyMatrix[i][j] = sum;
        sum = 0;
      }
    }        
		
    System.out.println("Multiplied Matrix : " );
    for(int i = 0; i < r1; i++){
      for(int j = 0; j < c2; j++){
        System.out.print(" " +multiplyMatrix[i][j]+"\t");
      }
      System.out.println();
    }
    if(in != null){
      in.close();
    }
  }

  private static int[][] prepareMatrix(int row, int column){
    Scanner sc = new Scanner(System.in);
    System.out.print("Enter elements of Matrix : ");
    int matrix[][] = new int[row][column];
    for(int i = 0; i < row; i++){
      for(int j = 0; j < column; j++){
        matrix[i][j] = sc.nextInt();
      }
    }
    System.out.println("Entered Matrix : " );
    for(int i = 0; i < row; i++){
      for(int j = 0; j < column; j++){
        System.out.print(" " +matrix[i][j]+"\t");
      }
      System.out.println();
    }
    return matrix;
  }
}
Output
Enter number of rows and columns in the matrix : 3 3
Enter elements of Matrix : 1 3 5 7 9 11 13 15 17
Entered Matrix : 
 1	 3	 5	
 7	 9	 11	
 13	 15	 17	
Enter number of rows and columns in the matrix : 3 3
Enter elements of Matrix : 2 4 6 8 10 12 14 16 18
Entered Matrix : 
 2	 4	 6	
 8	 10	 12	
 14	 16	 18	
Multiplied Matrix : 
 96	 114	 132	
 240	 294	 348	
 384	 474	 564	

That's all for the topic Matrix Multiplication Java Program. If something is missing or you have something to share about the topic please write a comment.


You may also like

Reverse an Array In-place Java Program

In this post we’ll see how to reverse an array in-place Java. Though it is easy to take another array and start storing elements from the last index to the first index of the original array to this new array in order to get reversed array but this approach means using auxiliary data structure, a new array to store the reversed elements making the space complexity of this approach O(n).

Using an in-place algorithm means additional space is not used and the space provided by the input data structure itself is used to modify the elements to get the output. Thus the Java program to reverse an array in-place will not use any additional array and swap elements with in the original array to get the reversed array as output.

Reverse array in-place Java program

One thing to note here is that you don’t need to iterate the whole array, you need to iterate only n/2 array for the array of size n. Since the first and last elements, second and second last and so on are swapped in each iteration so by the time middle element is reached the array is already reversed.

reverse array in place java
import java.util.Arrays;

public class ArrayReverseInplace {
  public static void main(String[] args) {
    int[] arr = {61, 34, 10, 0, 15, 112, 53, 78, 39, 68};
    reverseArray(arr);
  }

  static void reverseArray(int[] arr) {
    int n = arr.length;
    int temp;
    // Iterate till array length/2
    for (int i = 0; i < n / 2; i++) { 
      temp = arr[i]; 
      // Swapping
      arr[i] = arr[n - i - 1]; 
      arr[n - i - 1] = temp; 
    } 
    System.out.println("Reversed Array- " + Arrays.toString(arr));
  }
}
Output
Reversed Array- [68, 39, 78, 53, 112, 15, 0, 10, 34, 61]

As you can see in the Java program for reversing array in-place same input array space is used to do the reversal, only extra space required is for the auxiliary variables used.

That's all for the topic Reverse an Array In-place Java Program. If something is missing or you have something to share about the topic please write a comment.


You may also like

February 9, 2026

Matrix Subtraction Java Program

This post shows a Java program to subtract two matrices.

When you subtract two matrices you subtract the element at the same index in both matrices so you’ll subtract the element at index (0, 0) in the first matrix with the element at index (0, 0) in the second matrix to get the element at (0, 0) in the resultant matrix. Also note that both of the matrix have to be of the same order for subtraction.

For example– If you are subtracting two 3 X 3 matrices.

Matrix subtraction in Java

Java program for matrix subtraction

import java.util.Scanner;

public class MatrixSubtraction {

  public static void main(String[] args) {
    Scanner in = new Scanner(System.in);
    System.out.print("Enter number of rows and columns in the matrix : ");
    int row = in.nextInt();
    int column = in.nextInt();
    // First matrix
    int[][] matrix1 = prepareMatrix(row, column);
    
    // Second matrix
    int[][] matrix2 = prepareMatrix(row, column);
    // Subtraction result stored in this matrix
    int subtractMatrix[][] = new int[row][column];
    // Subtraction logic 
    for(int i = 0; i < row; i++){
      for(int j = 0; j < column; j++){
        subtractMatrix[i][j] = matrix1[i][j] - matrix2[i][j];
      }
    }
    
    System.out.println("Subtracted Matrix : " );
    for(int i = 0; i < subtractMatrix.length; i++){
      for(int j = 0; j < column; j++){
        System.out.print(" " +subtractMatrix[i][j]+"\t");
      }
      System.out.println();
    }
  }
	
  private static int[][] prepareMatrix(int row, int column){
    Scanner sc = new Scanner(System.in);
    System.out.print("Enter elements of Matrix : ");
    int matrix[][] = new int[row][column];
    for(int i = 0; i < row; i++){
      for(int j = 0; j < column; j++){
        matrix[i][j] = sc.nextInt();
      }
    }
    System.out.println("Entered Matrix : " );
    for(int i = 0; i < row; i++){
      for(int j = 0; j < column; j++){
        System.out.print(" " +matrix[i][j]+"\t");
      }
      System.out.println();
    }
    return matrix;
  }
}
Output
Enter number of rows and columns in the matrix :  3 3
Enter elements of Matrix : 1 3 8 2 9 3 0 5 11
Entered Matrix : 
 1	 3	 8	
 2	 9	 3	
 0	 5	 11	

Enter elements of Matrix : 0 2 4 6 7 8 2 3 5
Entered Matrix : 
 0	 2	 4	
 6	 7	 8	
 2	 3	 5
	
Subtracted Matrix : 
 1		1		4	
 -4		2		-5	
 -2		2		6	

That's all for the topic Matrix Subtraction Java Program. If something is missing or you have something to share about the topic please write a comment.


You may also like

How to Convert File to Byte Array in Java

This post shows different ways to convert file to byte array in Java.

  1. You can use read(byte[] b) method of FileInputStream class which reads up to b.length bytes of data from this input stream into byte array. See example.
  2. Java 7 onward you can use Files.readAllBytes() method which reads all the bytes from a file and return a byte array. See example.
  3. Apache CommonsIO also has methods IOUtils.toByteArray and FileUtils.readFileToByteArray to convert file to byte array. To use it you will have to put CommonsIO jar in your project’s classpath. See example.

Java program to convert file to byte array

Let’s see examples of converting file to byte array in Java using the above mentioned options.

Using read method of FileInputStream class

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.util.Arrays;

public class FileToBytearray {
  public static void main(String[] args) {
    File file = new File("D:\\test.txt");
    byte[] bArray = convertFileToByteArray(file);
    System.out.print(Arrays.toString(bArray));
  }
	
  private static byte[] convertFileToByteArray(File file){
    FileInputStream fis = null;
    // Creating bytearray of same length as file
    byte[] bArray = new byte[(int) file.length()];
    try{
      fis = new FileInputStream(file);
      // Reading file content to byte array
      fis.read(bArray);
      fis.close();                    
    }catch(IOException ioExp){
      ioExp.printStackTrace();
    }finally{
      if(fis != null){
        try {
          fis.close();
        } catch (IOException e) {
          // TODO Auto-generated catch block
          e.printStackTrace();
        }
      }
    }
    return bArray;
  }
}
Output
[49, 48, 48, 49, 124, 49, 48, 48, 51, 124, 50, 48, 48, 48, 13, 10, 49, 
48, 48, 54, 124, 50, 48, 48, 52, 124, 51, 48, 48, 48, 13, 10, 49, 48, 
48, 53, 124, 49, 48, 48, 55, 124, 49, 48, 48, 48, 48, 13, 10, 84, 104, 
105, 115, 32, 105, 115, 32, 97, 32, 116, 101, 115, 116, 32, 108, 105, 
110, 101, 46, 10, 76, 105, 110, 101, 32, 119, 114, 105, 116, 116, 101, 
110, 32, 98, 121, 32, 74, 97, 118, 97, 32, 112, 114, 111, 103, 114, 97, 
109, 32, 105, 110, 32, 107, 110, 112, 67, 111, 100, 101, 46, 99, 111, 
109, 46]

As you can see output is a series of bytes.

Using Files.readAllBytes() method to convert file to byte array

import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.Arrays;

public class FileToBytearray {
  public static void main(String[] args) {       
    Path path = Paths.get("D:\\test.txt");
    try {
      byte[] bArray = Files.readAllBytes(path);
      System.out.println(Arrays.toString(bArray));
    } catch (IOException e) {
      System.out.println("Error while converting " + e.getMessage());
    }    
  }
}

Using Apache CommonsIO utility methods

As already mentioned there are two methods that can be used for converting file to byte array if Apache CommonsIO is used.

  • IOUtils.toByteArray- This method takes FileInputStream object as argument.
  • FileUtils.readFileToByteArray- Pass instance of File as argument.
Using IOUtile.toByteArray
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.util.Arrays;
import org.apache.commons.io.IOUtils;

public class FileToBytearray {
  public static void main(String[] args) {       
    File file = new File("D:\\test.txt");
    try(FileInputStream fis = new FileInputStream(file)) {
      byte[] bArray;
      bArray = IOUtils.toByteArray(fis);
      System.out.println(Arrays.toString(bArray));
    } catch (IOException e) {
      // TODO Auto-generated catch block
      e.printStackTrace();
    }
  }
}
Using FileUtils.readFileToByteArray
import java.io.File;
import java.io.IOException;
import java.util.Arrays;
import org.apache.commons.io.FileUtils;

public class FileToBytearray {
  public static void main(String[] args) {       
    File file = new File("D:\\test.txt");
    byte[] bArray;
    try {
      bArray = FileUtils.readFileToByteArray(file);
      System.out.println(Arrays.toString(bArray));
    } catch (IOException e) {
      // TODO Auto-generated catch block
      e.printStackTrace();
    }	
  }
}

That's all for the topic How to Convert File to Byte Array in Java. If something is missing or you have something to share about the topic please write a comment.


You may also like

February 8, 2026

Matrix Addition Java Program

This post shows a Java program to add two matrices.

When you add two matrices you add the element at the same index in both matrices so you’ll add the element at index (0, 0) in the first matrix with the element at index (0, 0) in the second matrix to get the element at (0, 0) in the resultant matrix. Also note that both of the matrix have to be of the same order for addition.

For example– If you are adding two 3 X 3 matrices.

Matrix addition java program

Java program for matrix addition

import java.util.Scanner;
public class MatrixAddition {
  public static void main(String[] args) {
    Scanner in = new Scanner(System.in);
    System.out.print("Enter number of rows and columns in the matrix : ");
    int row = in.nextInt();
    int column = in.nextInt();
    // First matrix
    int[][] matrix1 = prepareMatrix(row, column);

    // Second matrix
    int[][] matrix2 = prepareMatrix(row, column);
    // addition result stored in this matrix
    int addedMatrix[][] = new int[row][column];
    // Addition logic 
    for(int i = 0; i < row; i++){
      for(int j = 0; j < column; j++){
        addedMatrix[i][j] = matrix1[i][j] + matrix2[i][j];
      }
    }
        
    System.out.println("Added Matrix : " );
    for(int i = 0; i < addedMatrix.length; i++){
      for(int j = 0; j < column; j++){
        System.out.print(" " +addedMatrix[i][j]+"\t");
      }
      System.out.println();
    }
  }
	
  private static int[][] prepareMatrix(int row, int column){
    Scanner sc = new Scanner(System.in);
    System.out.print("Enter elements of Matrix : ");
    int matrix[][] = new int[row][column];
    for(int i = 0; i < row; i++){
      for(int j = 0; j < column; j++){
        matrix[i][j] = sc.nextInt();
      }
    }
    System.out.println("Entered Matrix : " );
    for(int i = 0; i < row; i++){
      for(int j = 0; j < column; j++){
        System.out.print(" " +matrix[i][j]+"\t");
      }
      System.out.println();
    }
    return matrix;
  }
}
Output
Enter number of rows and columns in the matrix : 3 3
Enter elements of Matrix : 1 3 5 7 9 11 13 15 17
Entered Matrix : 
 1	 3	 5	
 7	 9	 11	
 13	 15	 17	
Enter elements of Matrix : 2 4 6 8 10 12 14 16 18
Entered Matrix : 
 2	 4	 6	
 8	 10	 12	
 14	 16	 18	
Added Matrix : 
 3	 7	 11	
 15	 19	 23	
 27	 31	 35	

That's all for the topic Matrix Addition Java Program. If something is missing or you have something to share about the topic please write a comment.


You may also like

February 7, 2026

Java Program to Find Maximum And Minimum Number in a Matrix

In this post we’ll see a Java program to find maximum and minimum number in a matrix or a 2D array.

Java program

Logic for finding the maximum and minimum number in a matrix goes as follows-

Initially assign the element at the index (0, 0) of the matrix to both min and max variables. Then iterate the matrix one row at a time and compare each element with the max variable first.

If max variable is less than the current element then assign the current element to the max variable, else compare current element with the min variable, if min variable is greater than the current element then assign the current element to the min element.

public class MaxAndMin {
  public static void main(String[] args) {
    Scanner in = new Scanner(System.in);
    System.out.print("Enter number of rows and columns in the matrix : ");
    int row = in.nextInt();
    int column = in.nextInt();
    // Prepare matrix
    System.out.print("Enter elements of Matrix : ");
    int matrix[][] = new int[row][column];
    for(int i = 0; i < row; i++){
      for(int j = 0; j < column; j++){
        matrix[i][j] = in.nextInt();
      }
    }
    System.out.println("Entered Matrix : " );
    for(int i = 0; i < row; i++){
      for(int j = 0; j < column; j++){
        System.out.print(" " +matrix[i][j]+"\t");
      }
      System.out.println();
    }
    // call method to find min and max in matrix
    findMinAndMax(matrix);
  }
 
  // Method to find maximum and minimum in matrix
  private static void findMinAndMax(int[][] matrix){     
    int maxNum = matrix[0][0];
    int minNum = matrix[0][0];
    for (int i = 0; i < matrix.length; i++) {
      for (int j = 0; j < matrix[i].length; j++) {
        if(maxNum < matrix[i][j]){ 
          maxNum = matrix[i][j]; 
        } else if(minNum > matrix[i][j]){
          minNum = matrix[i][j];
        }
      }
    }
    System.out.println("Max number: " + maxNum + 
          " Min number: " + minNum);
  }
}
Output
Enter number of rows and columns in the matrix : 3 3
Enter elements of Matrix : 3 6 12 34 19 5 32 16 7
Entered Matrix : 
 3	 6	 12	
 34	 19	 5	
 32	 16	 7	
Max number: 34 Min number: 3

That's all for the topic Java Program to Find Maximum And Minimum Number in a Matrix. If something is missing or you have something to share about the topic please write a comment.


You may also like

February 6, 2026

Java Program to Find The Maximum Element in Each Row of a Matrix

In this post we’ll see a Java program to find the maximum element in each row of a matrix.

For example if there is a matrix as given below-

10  8   6
0   13  7
17  3   15

Then program should find the maximum element for each row in the matrix as follows-

Maximum element in row-1 = 10

Maximum element in row-2 = 13

Maximum element in row-3 = 17

Java program - Finding max element in each row of a matrix

public class MatrixMaxElement {

  public static void main(String[] args) {
    Scanner in = new Scanner(System.in);
    System.out.print("Enter number of rows and columns in the matrix: ");
    int row = in.nextInt();
    int col = in.nextInt();
    // Prepare matrix
    int[][] matrix = prepareMatrix(row, col);
    findMaxInEachRow(matrix);
    in.close();
  }
  // Method to enter matrix elements
  private static int[][] prepareMatrix(int row, int column){
    Scanner sc = new Scanner(System.in);
    System.out.print("Enter elements of Matrix : ");
    int matrix[][] = new int[row][column];
    for(int i = 0; i < row; i++){
      for(int j = 0; j < column; j++){
        matrix[i][j] = sc.nextInt();
      }
    }
    sc.close();
    System.out.println("Entered Matrix : " );
    for(int i = 0; i < row; i++){
      for(int j = 0; j < column; j++){
        System.out.print(" " +matrix[i][j]+"\t");
      }
      System.out.println();
    }
    return matrix;
  }
  // Method to find the maximum element in each row
  private static void findMaxInEachRow(int[][] matrix){
    int[] tempArray = new int[matrix.length];
    for (int i = 0; i < matrix.length; i++) {
      // Start with first element of the row
      int max = matrix[i][0];
      for (int j = 0; j < matrix[i].length; j++) {
        if(max < matrix[i][j]){
          max = matrix[i][j];
        }
        tempArray[i] = max;
      }         
    }        
    // Displaying max elements
    for (int i = 0; i < tempArray.length; i++) {
      System.out.println("Maximum element in row-" + (i + 1) + " = " + tempArray[i]);
    }
  }
}
Output
Enter number of rows and columns in the matrix: 3 3
Enter elements of Matrix : 10 8 6
0 13 7
17 3 15
Entered Matrix : 
 10	 8	 6	
 0	 13	 7	
 17	 3	 15	
Maximum element in row-1 = 10
Maximum element in row-2 = 13
Maximum element in row-3 = 17

That's all for the topic Java Program to Find The Maximum Element in Each Row of a Matrix. If something is missing or you have something to share about the topic please write a comment.


You may also like