Intersection of two arrays in java with example

Before giving coding examples , We should understand first what is Intersection of two arrays is ?

Intersection of two arrays means finding out common elements or matching elements . Most of the algorithm based technical java interview served this question as a start up recipe to the students .
So one should prepare this question before appearing for the technical interview .

For example , Suppose we have given two arrays

array1  contains { 0 ,  1 , 2 ,  3 ,  4  ,  5  }
array2  contains  {  4 ,  7 , 8 , 9 , 10 , 1 }


Then intersection of array1 and array2 will be :    { 1 , 4  }


Pseudo algorithm :

1.   Print both given arrays
2.  Loop through first array till the first  array length
                     Inside first array loop,  loop the second array  till the length   of the second array
                             2.1       Compare elements of first array to the elements of the second array
                             2.2       If  first array element matches with second array element
                                              create new third  resulting array  and store the matching element in it
                                         else
                                         continue
3. Print the third resulting  array   showing intersection of the two given arrays


Demo : 




intersection of arrays in java with example














Code :



 public class Intersection {
    
    /**
    * @param args
    */
    
    static int i,j,k,c=0,w;
    
    public static void main(String[] args)
    {
        
        int[] x= {2,5,3,7};
        System.out.println("The first array is " +"  ");
        for(int i=0;i;x.length;i++)
        System.out.print(x[i]+"  ");
        System.out.println("");
        int[] y={5,2,9,0,1};
        System.out.println("The second array is " +"  ");
        for(int j=0;j;y.length;j++)
        System.out.print(y[j]+"  ");
        System.out.println("");
        intersection(x,y);
    }
    
    
    static void intersection(int x[],int y[])
    {
        int []z=new int[x.length+y.length];
        for(i=0;i <(x.length);i++)
        {
            for(j=0;j < y.length;j++)
            {
                if(x[i]==y[j])
                {
                    z[c]=x[i];
                    
                    c++;
                }
                
                else
                continue;
                
            }
        }
        System.out.println("Intersection of two  array is " +"  ");
        for(k=0;k < c;k++)
        {
            System.out.print("  "+z[k]+" ");
        }
        System.out.println("            ");
    }
    
}
 
 

About The Author

Subham Mittal has worked in Oracle for 3 years.
Enjoyed this post? Never miss out on future posts by subscribing JavaHungry