Count distinct elements of an array using java

Count distinct elements of an array

In this section, we will learn, how to print the distinct number in an array in java language.

Given an integer array, we have to print all the distinct element of the input array. input array may contain duplicate elements, we have to print one element only once.


input: a[]={10,20,10,9,6,2,6,20}

Output:  5

there are five distinct elements in the array.

they are  10,20,9,6,2

now we will see the java program and working to find the distinct element in the array.

Distinct element


Step 1. Initialize arrays.

Step 2. Declare the scanner class for taking input.

Step 3. take array size from the user.

Step 4. Take an element of the array from the user.

Step 5.  Print the total distinct number of the array by calling DCount function.


DCount(int a[], int n)

Step 1. Initialise temp variable with zero.

Step 2.  Initialise two for-loop for checking the similar elements.

Step 3.  check the condition if i and j are equal then increase a temporary variable by one.

Step 4. Return the main temporary variable.

Java program to count distinct elements of an array

import java.util.Scanner;
public class Main
    public static int DCount(int a[],int n)
        int res=0;
        for(int i=0;i<n;i++)
           int j;

           for (j = 0; j < i; j++)

           if (a[i] == a[j])

           if (i == j)
        return res;
public static void main(String[] args) 
Scanner sc=new Scanner(;
int[] a=new int[50];
    System.out.println("enter size of an array");
    int size=sc.nextInt();
    System.out.println("enter elements of an array");

    for(int i=0;i<size;i++)

System.out.println("total distinct number of element "+DCount(a,size));


enter size of an array
enter elements of an array
total distinct number of element 4

Please Login/Signup to comment