Java Program to find duplicate elements in array


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


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

Duplicate elements is: 12 23


Example: How to find duplicate elements in array in Java

Run it Now
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("\nDuplicate Elements is :");
        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 :1 5 4 5 5
Duplicate Elements is : 5