How to Find Common Elements Between Two Arrays in Java?

Before we go forward, we will learn about what is an array and how we can define it in java. Later we will see a program on how to Find Common Elements Between Two Arrays in Java.

An array is a data structure that is used to store data of the same datatype. Users can explicitly take the value of size or have to define it in the program before using it.

An array is useful in many ways. One such example of using array is if the user wants to store many numbers of the same datatype then he can do that by defining an array and not explicitly defining each number.

Syntax:

datatype[] arrayname;
or
datatype arrayname[];

Now it’s time to take our head to the problem that we want to solve. So carry on reading this article…

Below is given our program to find common elements between two arrays in Java.

import java.util.Scanner;

class commonElement {

 public static void main(String[] args) {

      Scanner sc = new Scanner(System.in);

      System.out.println("Enter the size of the array 1:");
      int size1 = sc.nextInt();

      int[] arrayEx1 = new int[size1];
      System.out.println("Enter the elements of the array1:");
  
      for(int i=0; i<arrayEx1.length; i++) {
         arrayEx1[i] = sc.nextInt();
      }

      System.out.println("Enter the size of the array 2:");
      int size2 = sc.nextInt();
      int[] arrayEx2 = new int[size2];

      System.out.println("Enter the elements of the array2:");
      for(int i=0; i<arrayEx2.length; i++) {
         arrayEx2[i] = sc.nextInt();
      }
      
  for(int i = 0; i < arrayEx1.length; i++){
   for(int j = 0; j < arrayEx2.length; j++){
    if(arrayEx1[i] == arrayEx2[j]){
     System.out.println("The commom element between two arrays is: "+arrayEx1[i]);
     break;
    }
   }
  }
  
 }
}

Explanation:

Here in our code, we have initialized two array name arrayEx1 and arrayEx2. Both of the arrays will take size and elements from the user. The method used here is a brute force approach for finding common elements of two arrays.

Also, read:

As we have applied nested for loop in which for one number in arrayEx1 it will check all numbers in arrayEx2. You can look at our program, you will find it. This will result in o(n2) complexity. When the number is found it will break the for loop after printing the result.

Leave a Reply