Java program to find frequency count for an array item
Problem Statement
Given an unsorted array of n integers. Elements can be repeated multiple times in the array. Write a java program to find frequency count of an array item.

Java Program
public class ArrayFrequency {
public static void main(String[] args) {
int n;
Scanner input = null;
int[] a = null;
try {
input=new Scanner(System.in);
System.out.println("Enter size of the array:");
n= input.nextInt();
if(n > 0) {
a=new int[n];
System.out.println("Enter array elements:");
for (int i = 0; i < n; i++) {
a[i] = input.nextInt();
}
}else{
System.out.println("Enter positive number.");
System.exit(0);
}
System.out.println("Input Array:");
printArray(a);
System.out.println("Enter the array element to
find frequency:");
int item= input.nextInt();
int count = frequencyCount(a,item);
if(count == 0 ) {
System.out.println("Item NOT FOUND in the array");
System.exit(0);
}
else{
System.out.println("Frequency count of item:" + count );
}
}catch (InputMismatchException ime) {
System.out.println("Not a valid input");
}
catch (Exception e) {
e.printStackTrace();
} finally {
if(input!=null)
{input.close();}
}
}
private static void printArray(int[] a){
for (int anA : a) {
System.out.print("[ " + anA + " ]");
}
System.out.println( "");
}
private static int frequencyCount(int[] a, int value) {
int frequency = 0;
for (int i=0; i<a.length; i++)
if (a[i] == value)
++frequency;
return frequency;
}
}
Run output of the program:

TestCase 1
Enter size of the array:
6
Enter array elements:
45
33
68
45
27
104
Input Array:
[ 45 ][ 33 ][ 68 ][ 45 ][ 27 ][ 104 ]
Enter the array element to find frequency:
45
Frequency count of item:2
TestCase 2
Enter size of the array:
6
Enter array elements:
45
33
68
45
27
104
Input Array:
[ 45 ][ 33 ][ 68 ][ 45 ][ 27 ][ 104 ]
Enter the array element to find frequency:
99
Item NOT FOUND in the array
—
Java Tutorial on this website:
https://www.testingdocs.com/java-tutorial/
For more information on Java, visit the official website :