Google News
logo
Java Program to Print the Duplicate Elements of an Array
In the following example of Java program to print the duplicate elements of an array :
Program :
import java.util.Arrays;

public class DuplicateElements {
    public static void main(String[] args) {
        int[] arr = {1, 2, 3, 4, 3, 5, 6, 2};
        int count = 0;
        
        System.out.println("Original Array: " + Arrays.toString(arr));
        
        for(int i=0; i<arr.length; i++){
            for(int j=i+1; j<arr.length; j++){
                if(arr[i] == arr[j]){
                    System.out.println("Duplicate element found: " + arr[j]);
                    count++;
                    break;
                }
            }
        }
        
        if(count == 0){
            System.out.println("No duplicate elements found.");
        }
    }
}
Output :
Original Array: [1, 2, 3, 4, 3, 5, 6, 2]
Duplicate element found: 2
Duplicate element found: 3
We have an integer array arr. We first print the original array using Arrays.toString() method. Then, we have two nested loops.

The outer loop is used to iterate through each element of the array. The inner loop is used to compare the current element with all the remaining elements of the array. If a duplicate element is found, we print it and increment the count variable.

We also break out of the inner loop, as we only need to print one instance of each duplicate element. Finally, we check if any duplicate elements were found, and if not, we print a message saying so.