Array Java Programs

Count the duplicate numbers in an array

In this tutorial you will learn how to count the number of occurrences of a number in an array Java.

The complete logic behind finding duplicate elements in array in C as:

  1. This program is about calculating the occurrences of each number specified by the user in an array.
  2. So we have tried to make this program very simple.
  3. Our program takes user’s input between 1 and 100 in an array.
  4. And in the second array we store the occurrence of the number.
  5. For the occurrence, we increase the value by one for the index which is equal to the number given by the user.
  6. For example, the first time at index 3 is 0. Now the user has given 3 as input for the first time, then we increase the number by 1 at index 3 for the second array.
  7. Now again the user has given 3 as input, then again we will increase the count by 1 for index 3 and now the count becomes 2.
  8. So we can say that the number 3 occurs 2 times.

How will our program behave?

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

Our program takes an array as input.

And based on the input, it will perform an operation to count the occurrence of all numbers.

Count the occurrence of numbers in Java array

import java.util.*;

public class ArrayExample {
	public static void main(String[] args) {
		Scanner sc = new Scanner(System.in);
		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();
			occur[arr[i]]++;
		}
		for (int i = 0; i < n; i++) {
			if (occur[i] > 1)
				System.out.println(i + " is occurs " + occur[i] + " times");
		}
	}
}

Output

Enter the size of array: 
5
Enter 5 array elements between 0 to 4
4
3
3
2
2
2 is occurs 2 times
3 is occurs 2 times

About the Author: Elavarasan PK

Technical Specialist, Intersoft Data Labs