How to Add Elements of two Arrays in Java - Example

One of the common programming exercise on various Java course is addition and multiplication of two arrays. How do you add two integer arrays in Java? Can you add two String array? 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 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 e.g. 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 length 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 array 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 e.g. byte, short, char, int, long, float and double etc, but you cannot add two Employee array or two Order array because you cannot define plus operator for them.




Program to add two arrays in Java

Here is our sample program to add two integer array 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 argumetns.

The array addition is simple, just add elemetns of same indices as shown in 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 which accepting an int array, you need to create several overloaded method for different array types if you wish to add them. This pattern is quite evident in java.uti.Arrays class which defines 8 or 9 sort method for sorting arrays of different types.

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

How to calculate sum of arrays in Java



Java Program to calculate 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 first example, we have passed two array of same type and same length and result is streightforward addition of elements at corresponding indices. On the second exmaple,  I have passed array of same type but different length hence result contains only 3 elements which is length of 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 bigger array with rest of elements intact. For more coding practice, you can also see Cracking the Coding Interview book, which contains over 189 quetsiosn rom programming interviews for practice.



That's all about how to add two arrays in Java. It's important to pay attention to type and length of the two arrays you are adding. You can only add a numeric array and string array. In the case of String array, an addition will be concatenation because + operator concat Strings. It's better if the arrays you are adding are of same length, but if they are different than you have choice 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 bubble sort algorithm? (solution)
  • How to find duplicate elements in array? (solution)
  • How to convert a LinkedList to array in Java? (example)
  • How to initialize a two dimensional array in Java? (example)
  • How to print array elements in readable format in Java? (solution)


No comments:

Post a Comment