Sum of Matrix Elements in Java

Program description:- Write a Java program to find the sum of matrix elements. Take a matrix, use a method to find the sum, and display the result.

Matrix =
1 2 3
4 5 6
7 8 9

Sum of matrix elements = 45

Before solving this problem, you should have knowledge of how to declare and initialize a matrix in Java, how to take input for a matrix from the end-user, and what are the different ways to display it. How to find the length or size of a matrix in Java? How to pass and return a matrix in Java. See:- Matrix in Java


Procedure to find the sum of matrix elements,
a) Take a matrix.
b) Declare a sum variable and initialize it with 0.
c) Traverse through the matrix.
d) Access each element of the matrix and add it to the sum variable.
e) Display the sum value.

Java Program to Find the Sum of Matrix Elements

public class Matrix {
  // main method
  public static void main(String[] args) {

    // declare and initialize matrix
    int a[][] = { { 1, 2, 3 }, { 4, 5, 6 }, { 7, 8, 9 } };

    // find sum of matrix elements
    int sum = matrixSum(a);

    // display result
    System.out.println("The sum of matrix elements = " + sum);

  // method to find sum of matrix elements
  public static int matrixSum(int[][] a) {

    // variable to store sum
    int sum = 0;
    // traverse through the matrix
    for (int[] row : a) {
      for (int element : row) {
        // add element
        sum += element;
    // return sum value
    return sum;


The sum of matrix elements = 45

See more matrix programs in Java:- 

  1. Program to Print 3×3 Matrix 
  2. Sum of Diagonal Elements of Matrix in Java 
  3. Row sum and Column sum of Matrix in Java
  4. Matrix Addition in Java
  5. Subtraction of two matrices in Java 
  6. Transpose of a Matrix in Java 
  7. Matrix Multiplication in Java
  8. Menu-driven program for Matrix operations

Also See:-

If you enjoyed this post, share it with your friends. Do you want to share more information about the topic discussed above or do you find anything incorrect? Let us know in the comments. Thank you!

Leave a Comment

Your email address will not be published. Required fields are marked *