Find the duplicate values of an array in Java


One of the most common ways to find duplicates is by using the brute force method, which compares each element of the array to every other element.Declare and initialize an array.Duplicate elements can be found using Nested loops. Any looping statement having another loop statement inside called nested loop. The same way for looping having more inner loop is called nested for loop.

The outer loop will iterate through the array from 0 to length of the array. The outer loop will select an element.If a match is found which means the duplicate element is found then, display the 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