Intersection of two arrays java Code Example

Last Updated On Thursday 14th Apr 2022
  • To Find the Intersection Of Two Arrays, you need to use the two loops.
  • The Outer loop is used to iterate elements from the first array.
  • While the second loop is used to iterate elements from the second array.
	public class IntersectionOfTwoArrays {
  public void intersect(int[] nums1, int[] nums2) {
    int[] newArray = new int[nums1.length];
    int count = 0;

    for (int i = 0; i < nums1.length; i++) {
      for (int j = 0; j < nums2.length; j++) {
        if (nums1[i] == nums2[j]) {
          newArray[count] = nums1[i];
          nums2[j] = Integer.MIN_VALUE;
          count++;
          break;
        }
      }
    }
    System.out.println("Repeated values are");
    for (int i = 0; i < count; i++)
      System.out.print(newArray[i] + " ");
  }

  public static void main(String[] args) {
    IntersectionOfTwoArrays twoArr = new IntersectionOfTwoArrays();

    int[] nums1 = {1,2,3,4,5,6,7};
    int[] nums2 = {9,8,7,6,5,4,3};

    twoArr.intersect(nums1, nums2);
  }
}