Sunday, January 14, 2024

How to Add Elements of two Arrays in Java - Example

One of the common programming exercises on various Java courses is the addition and multiplication of two arrays. How do you add two integer arrays in Java? Can you add two String arrays? how about other data types etc? These are some of the interesting questions because Java doesn't support operator overloading. You cannot use the plus operator to add two arrays in Java e.g. if you have two int arrays  a1 and a2, doing a3 = a1 + a2 will give a compile-time error. The only way to add two arrays in Java is to iterate over them and add individual elements and store them into a new array. 

This is also not easy because the array can be of different length, so you need to make some rules and apply them to your method like you can throw IllegalArgumentException if you get two arrays which are not of the same type and their length is different.

Alternatively, you can also allow an array of different lengths and just add as many elements as possible by adding extra elements of the bigger array with zero. This is what we have done in our example.

Regarding the second question, since the + operator can be used to concatenate two strings, you can also add two String arrays where the addition will produce a third array where each element is a concatenation of respective elements from the first and second array.

You can also add all numeric types of array, like byte, short, char, int, long, float and double, etc, but you cannot add two Employee arrays or two Order arrays because you cannot define plus operator for them.




Program to add two arrays in Java

Here is our sample program to add two integer arrays in Java.  This program has a static method to add two arrays. I have made the method static becuase it doesn't need any state, it's a utility method, accepts the input it required as method arguments.

The array addition is simple, just add elements of the same indices as shown in the following image:

How to add integer array in Java


Since every array has a different type in Java, e.g. you cannot pass a short array to a method that accepts an int array, you need to create several overloaded methods for different array types if you wish to add them. This pattern is quite evident in java.util.Arrays class which defines 8 or 9 sort methods for sorting arrays of different types.

You can see Core Java Volume 1 - Fundamentals to learn more about the different properties of the array in Java and the useful methods defined in the java.util.Arrays class.



Java Program to calculate the sum of two integer arrays

import java.util.Arrays;

/*
 * Java Program to add two integer arrays. Since Java
 * does't support operator overloading you cannot
 * add two arrays using + operator, instead you need
 * to loop over array and add each element one by one. 
 */
public class ArrayAddition {

    public static void main(String args[]) {

        // let's first create two arrays
        int[] even = { 2, 4, 6 };
        int[] odd = { 1, 3, 5 };

        // The operator + is undefined for the argument type(s) int[],
        // int[]
        // int[] result = even + odd; // this will not work

        int[] result = add(even, odd);
        System.out.println("first array: " + Arrays.toString(even));
        System.out.println("second array: " + Arrays.toString(odd));
        System.out.println("sum of array: " + Arrays.toString(result));

        // adding two array of different length in Java
        int[] prime = { 2, 3, 5, 7 };
        result = add(even, prime);
        System.out.println("first array: " + Arrays.toString(even));
        System.out.println("second array: " + Arrays.toString(prime));
        System.out.println("sum of array: " + Arrays.toString(result));
    }

    /**
     * Adds numbers of two arrays. if arrays are of Different length than only
     * addition only occur for as many elements in the small array.
     * 
     * @param first
     * @param second
     * @return
     */
    public static int[] add(int[] first, int[] second) {
        int length = first.length < second.length ? first.length
                : second.length;
        int[] result = new int[length];

        for (int i = 0; i < length; i++) {
            result[i] = first[i] + second[i];
        }

        return result;
    }

}

Output:
first array: [2, 4, 6]
second array: [1, 3, 5]
sum of array: [3, 7, 11]
first array: [2, 4, 6]
second array: [2, 3, 5, 7]
sum of array: [4, 7, 11]

You can see in the first example, we have passed two arrays of the same type and the same length and the result is straightforward addition of elements at corresponding indices. In the second example,  I have passed an array of the same type but different length hence result contains only 3 elements which is the length of the smaller array. 

This is just my choice for testing, you can implement this method as you wish too e.g. can return an array of length equal to a bigger array with the rest of the elements intact. For more coding practice, you can also see Cracking the Coding Interview book, which contains over 189 questions from programming interviews for practice.



That's all about how to add two arrays in Java. It's important to pay attention to the type and length of the two arrays you are adding. You can only add a numeric array and string array. In the case of a String array, an addition will be concatenation because + operator Concat Strings. 

It's better if the arrays you are adding are of the same length, but if they are different then you have a choice of how to program your sum() or add() method. In our case, we give precedence to a small array and ignore extra elements in the bigger array.


Related Java Array Tutorials for Programmers
  • How to reverse an array in place in Java? (solution)
  • How to sort an array using the bubble sort algorithm? (solution)
  • How to find duplicate elements in an array? (solution)
  • How to convert a LinkedList to an array in Java? (example)
  • How to initialize a two-dimensional array in Java? (example)
  • How to print array elements in a readable format in Java? (solution)

2 comments:

  1. Hi,

    I did this solution on the fly in an interview.

    So I followed below approach.
    - Converting array to Integer;
    - Adding the integer.
    - converting sum to array.

    Code Below
    public class Main {

    public static void main(String[] args) {

    int[] num1={2,2,0,0};
    int[] num2={1,2};
    int[] sumArray = sumArray(num1,num2);

    for (int i=0; i0){
    number /= 10;
    arrayLength ++;
    }
    int[] array = new int[arrayLength];
    int i = 0;

    while(origNumber > 0){
    array[i] = origNumber%10;
    origNumber /= 10;
    i++;
    }



    return revArray(array);
    }

    public static int[] revArray(int[] a){
    int[] revArray = new int[a.length];

    for(int i = 0; i<a.length; i++)
    {
    revArray[a.length-1-i] = a[i];
    }

    return revArray;
    }
    }

    ReplyDelete
    Replies
    1. Nice try, but will this solution work if array contains two digits or three digits numbers like 10 or 100?

      Delete

Feel free to comment, ask questions if you have any doubt.