Java Program to Find Frequency of Each Character in a String

  • Java program to count the occurrence of each character if a string.

In this java program, we have to count the frequency of occurrence of each character of a string and then print it on screen.

For Example,
Input String : Apple
A : 1 times
e : 1 times
l : 1 times
p : 2 times

To count the frequency of each alphabet, we will first take a string as input from user. We will use an integer array of length 256 to count the frequency of characters. Initialize frequency array element with zero, which means initially the count of all characters are zero.
Using a for loop, traverse input string and increment the count of every character of input string. Finally, traverse the frequency array and print the frequency of every character.

Java program to count each character of a string

package com.tcc.java.programs;

import java.util.Scanner;

/**
 * Java Program to Count Character of a String
 */
public class CharacterCount {
    public static void main(String args[]) {
        String str;
        int i, length, counter[] = new int[256];

        Scanner scanner = new Scanner(System.in);
        System.out.println("Enter a String");
        str = scanner.nextLine();

        length = str.length();

        // Count frequency of every character and store
        // it in counter array
        for (i = 0; i < length; i++) {
            counter[(int) str.charAt(i)]++;
        }
        // Print Frequency of characters
        for (i = 0; i < 256; i++) {
            if (counter[i] != 0) {
                System.out.println((char) i + " --> " + counter[i]);
            }
        }
    }
}
Output
Enter a String
APPLE
A --> 1
E --> 1
L --> 1
P --> 2
Enter a String
TECHCRASHCOURSE
A --> 1
C --> 3
E --> 2
H --> 2
O --> 1
R --> 2
S --> 2
T --> 1
U --> 1