Introduction
Finding the sum of each row in a 2D array is a common matrix operation in Java. Unlike calculating the sum of all elements in the matrix, this problem requires you to compute a separate total for every row.
The key idea is to calculate one row at a time, store its sum, and then move to the next row. This means the accumulator must be reset for every row, making this problem slightly different from finding the overall matrix sum.
In this tutorial, you'll learn multiple approaches to calculate the sum of each row in a 2D array, including nested loops and Java Streams, along with best practices, common mistakes, and practical examples.
Problem Statement
Given the following 2D array:
int[][] matrix = {
{1, 2, 3},
{4, 5, 6},
{7, 8, 9}
};
The expected row sums are:
Row 0 = 6
Row 1 = 15
Row 2 = 24
Or as an array:
[6, 15, 24]
Method 1: Using Nested Loops
The most common approach is to use nested loops and store the sum of each row in a separate array.
Java Program
import java.util.Arrays;
public class Main {
public static void main(String[] args) {
int[][] matrix = {
{1,2,3},
{4,5,6},
{7,8,9}
};
int[] rowSums = new int[matrix.length];
for (int row = 0; row < matrix.length; row++) {
int currentRowSum = 0;
for (int col = 0; col < matrix[row].length; col++) {
currentRowSum += matrix[row][col];
}
rowSums[row] = currentRowSum;
}
System.out.println(Arrays.toString(rowSums));
}
}
Output
[6, 15, 24]
Time Complexity
O(rows × columns)
Space Complexity
O(rows)
The extra space is used to store the sum of every row.
Method 2: Using Enhanced For Loop
The enhanced for loop makes the code cleaner and easier to understand.
Java Program
import java.util.Arrays;
public class Main {
public static void main(String[] args) {
int[][] matrix = {
{1,2,3},
{4,5,6},
{7,8,9}
};
int[] rowSums = new int[matrix.length];
int index = 0;
for (int[] row : matrix) {
int sum = 0;
for (int value : row) {
sum += value;
}
rowSums[index++] = sum;
}
System.out.println(Arrays.toString(rowSums));
}
}
Output
[6, 15, 24]
This approach is recommended when element indexes are not required.
Method 3: Using Java Streams
Java Streams provide a concise functional solution.
Java Program
import java.util.Arrays;
public class Main {
public static void main(String[] args) {
int[][] matrix = {
{1,2,3},
{4,5,6},
{7,8,9}
};
int[] rowSums = Arrays.stream(matrix)
.mapToInt(row -> Arrays.stream(row).sum())
.toArray();
System.out.println(Arrays.toString(rowSums));
}
}
Output
[6, 15, 24]
How It Works
Arrays.stream(matrix)creates a stream of rows.mapToInt()converts each row into its sum.toArray()stores all row sums in an integer array.
Handling Jagged Arrays
A jagged array contains rows with different lengths.
Fortunately, all three approaches work correctly because each row is processed independently.
Java Program
import java.util.Arrays;
public class Main {
public static void main(String[] args) {
int[][] jagged = {
{1,2},
{3,4,5},
{6}
};
int[] rowSums = new int[jagged.length];
for (int row = 0; row < jagged.length; row++) {
int sum = 0;
for (int col = 0; col < jagged[row].length; col++) {
sum += jagged[row][col];
}
rowSums[row] = sum;
}
System.out.println(Arrays.toString(rowSums));
}
}
Output
[3, 12, 6]
Since the inner loop uses matrix[row].length, each row is processed according to its own size.
Step-by-Step Explanation
Consider the following code:
for (int row = 0; row < matrix.length; row++) {
int currentRowSum = 0;
for (int col = 0; col < matrix[row].length; col++) {
currentRowSum += matrix[row][col];
}
rowSums[row] = currentRowSum;
}
Here's what happens:
- Create an array to store the sum of every row.
- The outer loop selects one row.
- Initialize
currentRowSumto0. - The inner loop adds every element in that row.
- Store the completed sum in
rowSums[row]. - Repeat the process for every remaining row.
The most important point is that currentRowSum is reset to zero for each row.
Internal Working
For the following matrix:
{
{1,2,3},
{4,5,6},
{7,8,9}
}
The calculation proceeds as follows:
Row 0
1 + 2 + 3 = 6
rowSums[0] = 6
Row 1
4 + 5 + 6 = 15
rowSums[1] = 15
Row 2
7 + 8 + 9 = 24
rowSums[2] = 24
Final Result
[6, 15, 24]
Unlike the total sum problem, the accumulator starts from 0 for every new row.
Real-Life Analogy
Imagine a teacher calculating the total marks of students sitting in each classroom row.
Instead of adding everyone's marks together, the teacher calculates the total for the first row, writes it down, resets the calculator, and repeats the process for the second row and the third row.
At the end, the teacher has separate totals for each row instead of one grand total.
Best Practices
- Reset the row sum before processing each row.
- Use
matrix[row].lengthinstead of hardcoded column values. - Store row sums in an array sized as
matrix.length. - Use enhanced for loops when indexes are unnecessary.
- Consider Java Streams for cleaner code in functional-style applications.
- Use
longinstead ofintif row sums may exceed the integer limit.
Common Mistakes
Forgetting to Reset the Accumulator
Incorrect:
int sum = 0;
for (int row = 0; row < matrix.length; row++) {
for (int col = 0; col < matrix[row].length; col++) {
sum += matrix[row][col];
}
rowSums[row] = sum;
}
This produces cumulative totals instead of individual row sums.
Correct:
for (int row = 0; row < matrix.length; row++) {
int sum = 0;
...
}
Using the Wrong Size for the Result Array
Incorrect:
int[] rowSums = new int[matrix[0].length];
Correct:
int[] rowSums = new int[matrix.length];
Hardcoding the Number of Columns
Incorrect:
for (int col = 0; col < 3; col++)
Correct:
for (int col = 0; col < matrix[row].length; col++)
Confusing Row Sum with Total Matrix Sum
A row sum calculates one total per row.
A matrix sum calculates one total for the entire array.
These are different problems and require different accumulator logic.
Expert Tips
- Resetting an accumulator inside the outer loop is a common programming pattern used in many grouping and aggregation problems.
- Once you have the row sums, calculating the grand total becomes simple:
int grandTotal = 0;
for (int sum : rowSums) {
grandTotal += sum;
}
- The same approach can be adapted to calculate averages, maximum values, minimum values, and other statistics for each row.
- Java Streams provide an elegant solution for processing each row independently while keeping the code concise.
Comparison of Approaches
| Method | Handles Jagged Arrays | Output | Readability |
|---|---|---|---|
| Nested loops | ✅ Yes | int[] |
High |
| Enhanced for loop | ✅ Yes | int[] |
Very High |
| Java Streams | ✅ Yes | int[] |
High |
Frequently Asked Questions
What is the difference between row sum and total matrix sum?
A row sum calculates a separate total for each row, whereas a total matrix sum calculates one overall total for the entire matrix.
Why should the accumulator be reset?
Each row requires an independent total. Resetting the accumulator ensures that previous row values are not included.
How do I store row sums?
Create an integer array with the same size as the number of rows:
int[] rowSums = new int[matrix.length];
Does this work for jagged arrays?
Yes. Using matrix[row].length allows each row to be processed according to its own size.
Can I calculate the grand total from row sums?
Yes. Simply sum all values stored in the rowSums array.
Is the Streams approach faster?
For most applications, performance is similar. Nested loops are slightly more efficient, while Streams provide more concise and expressive code.
What happens if a row is empty?
Its sum will be 0, and the program continues normally without any special handling.
Can this approach be extended to 3D arrays?
Yes. Add another nested loop (or another stream operation) to process the additional dimension.