Character Frequency in Java: Explanation & Practice

Count frequency of each character

Problem summary

Write a program that counts the frequency of each character in a string.

Starter code

public class Main {
    public static void main(String[] args) {
        String text = "hello"; // Test case 1
        
        // Count and print frequency of each unique char
        // Format: <char>: <count> (one per line, alphabetical order)
    }
}

Expected output and test cases

  • hello frequencies
    e: 1
    h: 1
    l: 2
    o: 1
  • aaabb frequencies
    a: 3
    b: 2
  • Single character
    a: 1

Hints

  1. Use array or HashMap for counts
  2. Iterate through string once
  3. Sort characters for ordered output

Related Strings exercises

Practice all Strings exercises · Run this idea in the Java compiler