Count Frequency of Each Character in a String in Java — Definition, Examples and Program

Learn how to count the frequency of each character in a string using Java. This blog explains the logic, examples, and a clean Java program for beginners and interview preparation.

Count Frequency of Each Character in a String in Java

Counting the frequency of each character means finding how many times every character appears in a string. This is one of the most important string problems and forms the base for many advanced problems like anagrams, duplicates, and compression.

Character frequency counting is commonly used in:

How the Logic Works

  1. Create an array to store frequency of characters.
  2. Traverse the string character by character.
  3. Increase count for each character.
  4. Print characters with their frequency.

Example 1

Input: "programming"

Example 2

Input: "Java"

Java Program to Count Frequency of Each Character


import java.util.Scanner;

public class CharacterFrequency {

    public static void main(String[] args) {

        Scanner sc = new Scanner(System.in);

        System.out.print("Enter a string: ");
        String str = sc.nextLine().toLowerCase();

        int[] freq = new int[256];

        for (int i = 0; i < str.length(); i++) {
            char ch = str.charAt(i);
            if (ch != ' ') {
                freq[ch]++;
            }
        }

        System.out.println("Character Frequencies:");

        for (int i = 0; i < 256; i++) {
            if (freq[i] > 0) {
                System.out.println((char) i + " -> " + freq[i]);
            }
        }
    }
}

Sample Output


Enter a string: success
Character Frequencies:
s -> 3
u -> 1
c -> 2
e -> 1

Important Notes

Practice Challenges

  1. Count frequency using HashMap instead of array.
  2. Print frequencies in sorted order.
  3. Count frequency of words instead of characters.

Character frequency counting is a foundational skill for mastering string manipulation problems in Java.