belongs to collection: Array Programs in Java with Examples
Write a Java program to find the common elements between two arrays
In this demo I have used NetBeans IDE 8.2 for debugging purpose. But you can use any java programming language compiler as per your availability..
import java.util.Arrays; public class Javaexcercise { public static void main(String[] args) { int[] array1 = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10}; int[] array2 = {11, 10, 12, 13, 14, 2, 4, 5}; System.out.println("First Array : "+Arrays.toString(array1)); System.out.println("Second Array : "+Arrays.toString(array2)); for (int i = 0; i < array1.length; i++) { for (int j = 0; j < array2.length; j++) { if(array1[i] == (array2[j])) { System.out.println("Common element : "+(array1[i])); } } } } }
Result:
First Array : [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
Second Array : [11, 10, 12, 13, 14, 2, 4, 5]
Common element : 2
Common element : 4
Common element : 5Common element : 10
total answers (1)
start bookmarking useful questions and collections and save it into your own study-lists, login now to start creating your own collections.
In this demo I have used NetBeans IDE 8.2 for debugging purpose. But you can use any java programming language compiler as per your availability..
Result:
First Array : [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
Second Array : [11, 10, 12, 13, 14, 2, 4, 5]
Common element : 2
Common element : 4
Common element : 5Common element : 10
need an explanation for this answer? contact us directly to get an explanation for this answer