Java Program to Count the duplicate numbers in an array

In this tutorial, you will learn how do you count the number of occurrences of a number in an array java.

The Complete logic behind findings duplicate elements in array in c as:

  • In this program our focus is to calculate the occurrence of each number given by the user in an array.
  • So We have tried to make this program very simple.
  • Our program will take inputs from the users between 1 to 100 in one array.
  • And in second array  we are storing the occurrence of number.
  • For the occurrence we are increasing the value by one for the index which is equal to the number given by user.
  • For example first time at index 3 value is 0. Now user have given 3 first time as a input then we will increase count by 1 at the index 3 for second array. 
  • Now again user has given 3 as an input then we will again increase the count by 1 for index 3 and now count become 2. 
  • So we can say that occurrence of 3 is 2 times.

How our program will behave?

As we have already seen above our logic for finding the occurrence of numbers.

Our program will take an array as an input.

And on the basis of inputs it will perform some operation to count the occurrence of all numbers.

Java Program to count the occurrence of numbers in an array

import java.util.*;  
public class Main {  
    public static void main(String[] args) {  
      Scanner sc = new Scanner(;
      System.out.println("Enter the size of array: ");
      int n = sc.nextInt();
      int arr[] = new int[n];
      int occur[] = new int[n];
      Arrays.fill(occur, 0);
      System.out.println("Enter " +n+ " array elements between 0 to "+(n-1));
      for(int i=0; i<n; i++) {
         arr[i] = sc.nextInt();
      for(int i=0; i<n; i++) {
            System.out.println(i +" is occurs "+ occur[i] + " times");


count repeated elements in an array java

Leave a Comment