Here’s a Java program to find the intersection of two arrays:
import java.util.HashSet;
import java.util.Scanner;
import java.util.Set;
public class Intersection {
public static void main(String[] args) {
int[] arr1 = new int[5];
int[] arr2 = new int[5];
Scanner scanner = new Scanner(System.in);
System.out.println("Enter 5 numbers for the first array: ");
for (int i = 0; i < 5; i++) {
arr1[i] = scanner.nextInt();
}
System.out.println("Enter 5 numbers for the second array: ");
for (int i = 0; i < 5; i++) {
arr2[i] = scanner.nextInt();
}
int[] intersection = findIntersection(arr1, arr2);
System.out.print("Intersection of the two arrays: ");
for (int i = 0; i < intersection.length; i++) {
System.out.print(intersection[i] + " ");
}
}
public static int[] findIntersection(int[] arr1, int[] arr2) {
Set set1 = new HashSet<>();
Set set2 = new HashSet<>();
for (int i = 0; i < arr1.length; i++) {
set1.add(arr1[i]);
}
for (int i = 0; i < arr2.length; i++) {
set2.add(arr2[i]);
}
set1.retainAll(set2);
int[] intersection = new int[set1.size()];
int i = 0;
for (int num : set1) {
intersection[i++] = num;
}
return intersection;
}
}
In this program, we first create two integer arrays of size 5 and take user input for their elements using two for loops. We then call the `findIntersection()` method to find the intersection of the two arrays.
The `findIntersection()` method takes two integer arrays as parameters and returns an integer array containing their intersection. We first create two hash sets `set1` and `set2` and add the elements of the two arrays to them using for loops. We then call the `retainAll()` method on `set1` with `set2` as an argument to retain only the common elements between the two sets. We then create a new integer array `intersection` with the same size as the size of `set1`. We use a for-each loop to iterate over the elements of `set1` and add them to the `intersection` array. We then return the `intersection` array, which contains the common elements between the two arrays.
At the end of the program, we print out the intersection of the two arrays.