w3resource

Java: Find the common elements between two arrays of integers


15. Common elements in two integer arrays

Write a Java program to find common elements between two integer arrays.

Pictorial Presentation:

Java Array Exercises: Find the common elements between two arrays of integers


Sample Solution:

Java Code:

// Import the necessary Java utilities package.
import java.util.Arrays;
// Define a class named Exercise15.
public class Exercise15 {
    // The main method where the program execution starts.
    public static void main(String[] args) {
        // Declare and initialize two integer arrays, array1 and array2.
        int[] array1 = {1, 2, 5, 5, 8, 9, 7, 10};
        int[] array2 = {1, 0, 6, 15, 6, 4, 7, 0};

        // Print the original contents of array1 and array2.
        System.out.println("Array1 : " + Arrays.toString(array1));
        System.out.println("Array2 : " + Arrays.toString(array2));

        // Iterate through both arrays to find and print common elements.
        for (int i = 0; i < array1.length; i++) {
            for (int j = 0; j < array2.length; j++) {
                // Check if elements in array1 and array2 are equal.
                if (array1[i] == (array2[j])) {
                    // Print the common element.
                    System.out.println("Common element is : " + (array1[i]));
                }
            }
        }
    }
}

Sample Output:

Array1 : [1, 2, 5, 5, 8, 9, 7, 10]                                                                            
Array2 : [1, 0, 6, 15, 6, 4, 7, 0]                                                                            
Common element is : 1                                                                                         
Common element is : 7

Flowchart:

Flowchart: Java exercises: Find the common elements between two arrays of integers


For more Practice: Solve these Related Problems:

  • Write a Java program to find the union of two integer arrays.
  • Write a Java program to find common elements between three different integer arrays.
  • Write a Java program to find and count the number of common elements between two arrays.
  • Write a Java program to find common elements while ignoring duplicate occurrences.

Go to:


PREV : Common elements in two string arrays.
NEXT : Remove duplicates from array.

Java Code Editor:

What is the difficulty level of this exercise?

Test your Programming skills with w3resource's quiz.



Follow us on Facebook and Twitter for latest update.