w3resource

Java: Find the common elements between two arrays

Java Array: Exercise-14 with Solution

Write a Java program to find common elements between two arrays (string values).

Pictorial Presentation:

Java Array Exercises: Find the common elements between two arrays

Sample Solution:

Java Code:

// Import the necessary Java utilities package.
import java.util.*;

// Define a class named Exercise14.
public class Exercise14 {
    // The main method where the program execution starts.
    public static void main(String[] args) {
        // Declare and initialize two string arrays, array1 and array2.
        String[] array1 = {"Python", "JAVA", "PHP", "C#", "C++", "SQL"};
        String[] array2 = {"MySQL", "SQL", "SQLite", "Oracle", "PostgreSQL", "DB2", "JAVA"};

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

        // Create a HashSet to store common elements.
        HashSet set = new HashSet();

        // Iterate through both arrays to find and store 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].equals(array2[j])) {
                    // Add the common element to the HashSet.
                    set.add(array1[i]);
                }
            }
        }

        // Print the common elements.
        System.out.println("Common element : " + (set)); // OUTPUT: [SQL, JAVA]
    }
}

Sample Output:

Array1 : [Python, JAVA, PHP, C#, C++, SQL]                                                                    
Array2 : [MySQL, SQL, SQLite, Oracle, PostgreSQL, DB2, JAVA]                                                  
Common element is : [JAVA, SQL]

Flowchart:

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

Java Code Editor:

Previous: Write a Java program to find the duplicate values of an array of string values.
Next: Write a Java program to find the common elements between two arrays of integers.

What is the difficulty level of this exercise?

Test your Programming skills with w3resource's quiz.



Become a Patron!

Follow us on Facebook and Twitter for latest update.

It will be nice if you may share this link in any developer community or anywhere else, from where other developers may find this content. Thanks.

https://w3resource.com/java-exercises/array/java-array-exercise-14.php