Java program to count distinct element in an array

Count distinct element in 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
they are  10,20,9,6,2

java program to count-distinct elements in an array


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 D Count function.


D Count(int a[], int n)

Step 1. Initialze temp variable with zero.

Step 2.  Initialize 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 code

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));
Elements of array
12  2  12  3  9
Distinct elements are 
12  3  9