How to print common elements in two arrays in java?

This tutorial explain how to print common elements in two arrays in java.

Steps :

1) Create two input arrays and initialize with elements.

2) Take each element in first array and compare with each element in second array if they are equal print the elements.

Java example to print common elements in two arrays:

public class ArraysCommonElements {

	public static void main(String[] args) {

		int [] array1={1,2,3,4,5};
		int [] array2={3,4,5};

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

			}

		}

	}

}

 

Leave a Reply

Your email address will not be published. Required fields are marked *