Start Coding Now
📝 String Programsintermediate1 methods

Find Frequency of Characters in a String in Java

Program to count the occurrence of each character in a string.

Last updated: 11 January 2026

Method 1: Using HashMap

Map stores character count.

import java.util.HashMap;

public class Frequency {
    public static void main(String[] args) {
        String str = "hello world";
        HashMap<Character, Integer> frequency = new HashMap<>();
        
        for(char c : str.toCharArray()) {
            if(frequency.containsKey(c)) {
                frequency.put(c, frequency.get(c) + 1);
            } else {
                frequency.put(c, 1);
            }
        }
        
        System.out.println(frequency);
    }
}
Output:
{d=1, e=1, h=1, l=3, o=2, r=1, w=1,  =1}

Explanation

Using HashMap to store character as key and count as value.

Frequently Asked Questions

Try This Program

Copy this code and run it in our free online Java compiler.

Open Java Compiler