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

Xiith is created for educational, experimental, and schooling purpose. Examples on Xiith are made easier to make a better or basic understanding. Tutorials, testimonials, and examples are continuously checked to avoid delusion, but we cannot take complete responsibility of all programs on Xiith. When you are operating this site, you have to agree to read and accept our terms of use, cookie and privacy policy.Copyright © 2020 by Xiith. All Rights Reserved. About us.