Find the duplicate values of an array in Java


This program prints the duplicate elements in an integer array named 'a'. It uses nested for loops to compare each element with all other elements to find the duplicates. If two elements are found to be the same and have different indices, then it is considered a duplicate, and the value of the duplicate element is printed.

The outer loop iterates through each element of the array, while the inner loop iterates through all the remaining elements of the array. The condition (a[i] == a[j]) && (i != j) checks if the elements at index i and index j are equal and not the same element (with the same index). If this condition is true, then the program prints the value of the duplicate element.

Source Code

public class duplicate_array {
    public static void main(String args[]) {
        //Write a program to print the duplicate element in an array
        int[] a = {1, 2, 5, 5, 6, 6, 7, 2};
 
        for (int i = 0; i < a.length - 1; i++) {
            for (int j = i + 1; j < a.length; j++)
            {
                if ((a[i] == a[j]) && (i != j)) {
                    System.out.println("Duplicate Element : " + a[j]);
                }
            }
        }
 
    }
}
 

Output

Duplicate Element : 2
Duplicate Element : 5
Duplicate Element : 6
To download raw file Click Here

Basic Programs