Write a java program to find sum of common element in array.

Write a program to read two integer arrays and find the sum of common elements in both the arrays. If there are no common elements return -1 as output.

The return type (integer) should be the sum of common elements.

Assume that all the elements will be distinct.

Input and Output Format:

Input consists of 2n+1 integers. The first integer input corresponds to n, the number of elements in the array. The next ‘n’ integers correspond to the elements in the array, The last n elements correspond to the elements of the second array.

Output consists of a single Integer value.

Refer sample output for formatting specifications.


Assume that the maximum number of elements in the array is 20.


Sample Input 1:










Sample Output 1:


Find the sum of the common element in the array in Java.

import java.util.Scanner;

public class Main {
  public static void main(String[] args) {

    Scanner sc = new Scanner(System.in);
    int n = Integer.parseInt(sc.nextLine());
    int[] a = new int[n];
    int[] b = new int[n];
    for (int i = 0; i < n; i++)
      a[i] = Integer.parseInt(sc.nextLine());
    for (int i = 0; i < n; i++)
      b[i] = Integer.parseInt(sc.nextLine());
    System.out.println(display(a, b));


  public static int display(int a[], int b[]) {

    int sum = 0;
    for (int i = 0; i < a.length; i++) {
      for (int j = 0; j < b.length; j++) {
        if (a[i] == b[j])
          sum = sum + a[i];
    if (sum == 0)
      return -1;
      return sum;

Add a Comment

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

seventeen − 15 =