Sure, here’s a Java program to find the common elements between two arrays:
import java.util.Arrays; public class CommonElements { public static void main(String[] args) { int[] array1 = {1, 2, 3, 4, 5}; int[] array2 = {3, 4, 5, 6, 7}; int[] common = findCommonElements(array1, array2); System.out.println("Common elements: " + Arrays.toString(common)); } public static int[] findCommonElements(int[] array1, int[] array2) { int[] temp = new int[Math.min(array1.length, array2.length)]; int index = 0; for (int i = 0; i < array1.length; i++) { for (int j = 0; j < array2.length; j++) { if (array1[i] == array2[j]) { temp[index++] = array1[i]; break; } } } return Arrays.copyOf(temp, index); } }
In this program, we have two arrays `array1` and `array2`, and we want to find the common elements between them. We call the `findCommonElements()` method to find the common elements and store the result in a new array `common`.
The `findCommonElements()` method initializes a temporary array `temp` with a size equal to the minimum length of the two input arrays. Then, it loops through each element of `array1` and `array2`, comparing each element to find common elements. If a common element is found, it is added to the `temp` array and the index is incremented. Finally, the `temp` array is copied to a new array of the appropriate size using the `Arrays.copyOf()` method.
Finally, we print the common elements to the console using the `println()` method.
Note that this program assumes that the arrays do not contain duplicates. If the arrays may contain duplicates, you can use a `Set` to store the common elements instead of an array to eliminate duplicates.