How to Find Duplicate Elements in an Array – Java Program | Java Interview Question and Answer
How to Find Duplicate Elements in an Array - Java Program
How to Find Duplicate Elements in an Array – Java Program

Steps to find the Duplicate Element in an Array:

  1. First, we will initialize an array that has two duplicate elements 1 and 2
  2. We will write two for loops
  3. first for loop will go through each element in the array
  4. second for loop will compare the current element with all elements in the array
  5. If a match is found in the ‘if’ condition, the program will print out the duplicate element.

Example:

package TestAutomationCentral;

public class FindDuplicateElement {
public static void main(String[] args) {
//TestAutomationCentral.com
int[] arr = {1,2,3,4,5,1,2};
for(int i=0;i<arr.length-1;i++){
for(int j=i+1;j<arr.length;j++){
if(arr[i] == arr[j]){
System.out.println("Duplicate Element: "
+ arr[i]);
}
}
}
}
}
Share

Leave a Reply