How to find out common elements between two arrays

🔗 Find Common Numbers Between Two Arrays (Java)

🧩 What problem are we solving?

Given two arrays of integers, the goal is to find and print all the numbers that appear in both arrays — i.e., the common elements or intersection of the two arrays.

For example:
If we have

Array 1 = [12, 13, 14, 15, 16, 17] Array 2 = [12, 18, 29, 15, 7, 17]

then the numbers common to both are 12, 15, and 17.


⚙️ How it works (step by step)

  1. Start with two arrays of integers.

  2. Loop through each element of the first array (array1).

  3. For each element in array1, loop through the second array (array2).

  4. If a match is found (array1[i] == array2[j]), print or store that number.

  5. Continue until all elements have been compared.

This approach compares every element in array1 with every element in array2, ensuring all common numbers are identified.


🧠 Example Walkthrough

StepCompareMatch?Common Numbers Found
112 vs 1212
213 vs all12
314 vs all12
415 vs 1512, 15
516 vs all12, 15
617 vs 1712, 15, 17

Output:

12 15 17


package com.vinod.test;


/**
 * Class to find common numbers from two arrays
 *
 *@authorvinodkariyathungalkumaran
 *
 */
public class FindCommonNumbers {

public static void main(String[] args) {
int array1[] = { 12, 13, 14, 15, 16, 17 };
int array2[] = { 12, 18, 29, 15, 7, 17 };

for (int i = 0; i < array1.length; i++) {
for (int j = 0; j < array2.length; j++) {
if (array1[i] == array2[j]) {
System.out.println(array1[i]);
}
}
}

}

}

Output

12
15
17


No comments:

Post a Comment

12 classic String-based Java interview questions with simple explanations and code.

  1️⃣ Check if a String is a Palindrome Problem Given a string, check if it reads the same forward and backward. Example: "madam...

Featured Posts