Core Java

Computing the Sum of Two Arrays in Java

When working with arrays in Java, it is often necessary to perform various operations on them. One task could be to calculate the sum of two arrays. In this article, we will explore different methods to compute the element-wise sum of two arrays in Java and provide code examples.

1. Introduction

In Java, in order to compute the element-wise sum of two arrays, it is essential for both arrays to have identical types and sizes. Attempting to perform this operation with arrays of different types or sizes will result in an IllegalArgumentException.

To resolve this issue, it is necessary to create a third array of the same size and store the sums of corresponding elements from the original arrays in this new array.

To provide you with an example, If we consider the first array, array1[], with values {6, 7, 8, 9, 10}, and the second array, array2[], with values {1, 2, 3, 4, 5}, the result after adding these arrays will be as follows: [7, 9, 11, 13, 15] stored in a third array, array3[].

The rest of this article will explore different methods to accomplish this task in Java.

2. Method 1: Using Loops

When we need to calculate the sum of two arrays, we can employ loops to iterate through the elements of the arrays and perform the addition.

2.1 Using For Loops

Using a for Loop, we can iterate through both arrays simultaneously and add the corresponding elements from each array. Below is a simple example:

public class SumArrays {

    public static void main(String[] args) {

        int[] array1 = {6, 7, 8, 9, 10};
        int[] array2 = {1, 2, 3, 4, 5};

        // Create an array to store the sum
        int[] result = new int[array1.length];

        for (int i = 0; i < array1.length; i++) {
            // Calculate the sum element by element
            result[i] = array1[i] + array2[i]; 
        }

        // Print the sum array
        System.out.println("Sum Array: " + Arrays.toString(result));
    }
}

In this example, we create two arrays named array1 and array2 and a third array named result to store the result. We then use a for loop to iterate through the arrays and calculate the sum of corresponding elements. This is done by using the loop index (i) to access the elements at the same position in both arrays and then add them together.

The sum of these elements is then stored in the corresponding position in result. The above code will result in the output shown in Fig 1.

Fig 1: Output from computing the element-wise sum of two arrays using for loop in Java
Fig 1: Output from computing the element-wise sum of two arrays using for loop in Java

2.2 Using Enhanced For Loops

We can also calculate the sum of two arrays in Java using an enhanced for loop, also known as a for-each loop. Here is a simple example:

public class SumArrayUsingForEach {

      public static void main(String[] args) {
          
        int[] array1 = {6, 7, 8, 9, 10};
        int[] array2 = {1, 2, 3, 4, 5};

        //Create a third array to store the sum
        int[] sumArray = new int[array1.length];

        // Initialize an index variable to keep track of the current position in sumArray
        int i = 0; 

        for (int num1 : array1) {
            int num2 = array2[i];
            sumArray[i] = num1 + num2;
            i++;
        }

        // Display the sumArray
        System.out.println("Sum Array: " + Arrays.toString(sumArray));
        }
    }

In the code above, we start by creating two arrays that we want to add together and name them array1 and array2. We then create a third array named sumArray to store the sum specifying that the length of this array should be equal to the length of the input arrays.

Next, we use an enhanced for loop to iterate through the elements of the arrays. In each iteration, we add the elements from array1 and array2 and store the result in the corresponding position of the sumArray.

In the for loop, we create two int variables, num1 to represent the current element in array1, and num2 to represent the corresponding element in array2. We then add them together and store the results in sumArray. We use an int variable i to keep track of the current position in sumArray.

When the loop is done, sumArray will contain the sum of the two input arrays and the output will be:

Sum Array: [7, 9, 11, 13, 15]

3. Method 2: Using Java Stream API

Java Streams provides an efficient and more concise way to process data, simplifying operations on arrays and collections. To calculate the sum of two arrays using Java Streams, we can leverage the IntStream class like this:

public class SumArrayJavaStreams {

    public static void main(String[] args) {

        int[] array1 = {6, 7, 8, 9, 10};
        int[] array2 = {1, 2, 3, 4, 5};

        // Ensure both arrays are of the same length
        if (array1.length != array2.length) {
            System.out.println("Arrays must have the same length for addition.");
            return;
        }

        int[] sumArray = IntStream.range(0, array1.length)
                .map(i -> array1[i] + array2[i])
                .toArray();

        // Display the sumArray
       System.out.println("Sum Array: " + Arrays.toString(sumArray));
    }
}

In the code above, after creating two arrays named array1 and array2, we check that both arrays are of the same length to ensure element-wise addition is possible.

We then use IntStream.range(0, array1.length) to create a stream of integers from 0 to the length of the arrays. This stream of indices is used to access corresponding elements from both array1 and array2.

Next, we use the map operation .map(i -> array1[i] + array2[i]) to map each index i to the sum of array1[i] and array2[i]. This method calculates the sum of these elements and stores them in the sumArray variable.

Finally, we use the .toArray() method to collect the IntStream back into an integer array. After executing the code above, sumArray will contain the sum of the two input arrays and the output is:

Sum Array: [7, 9, 11, 13, 15]

4. Conclusion

In this article, we explored how to calculate the sum of two array elements based on their respective indices and store the results in a separate array using Java.

In conclusion, There are multiple ways to calculate the sum of two arrays in Java. The method to choose depends on our specific requirements and coding style. We can use traditional for loops or the Stream API which provides an elegant and more efficient way to create concise and readable code for array manipulation in Java.

5. Download the Source Code

This was an example of Computing the Sum of Two Arrays in Java.

Download
You can download the full source code of this example here: Computing the Sum of Two Arrays in Java

Omozegie Aziegbe

Omos holds a Master degree in Information Engineering with Network Management from the Robert Gordon University, Aberdeen. Omos is currently a freelance web/application developer who is currently focused on developing Java enterprise applications with the Jakarta EE framework.
Subscribe
Notify of
guest

This site uses Akismet to reduce spam. Learn how your comment data is processed.

0 Comments
Inline Feedbacks
View all comments
Back to top button