Java Program to find duplicate elements in the array


In this program, You will learn how to find duplicate elements in an array in java.


List is: 1, 2, 12, 23, 12, 23

Duplicate elements are: 12 23

Example: How to find duplicate elements in an array in java

import java.util.Scanner;

class Main {
    public static void main(String args[]) {

        int i, j, v = 1;
        int arr[] = new int[5];
        Scanner sc = new Scanner(System.in);

        System.out.print("Enter 5 numbers:");

        for (i = 0; i < 5; i++) {
            arr[i] = sc.nextInt();
        }

        System.out.print("Duplicate elements:");
        for (i = 0; i < 5; i++) {
            for (j = i + 1; j < 5; j++) {
                if (arr[i] == arr[j]) {
                    if (v == 1 && arr[j] != '\0') {
                        System.out.print(" " + arr[i]);
                    }
                    arr[j] = '\0';
                    v++;
                }
            }
            v = 1;
        }

    }
}

Output:

Enter 5 numbers:10 20 10 20 30
Duplicate elements: 10 20