How to count the frequency of a character in a string in Java


If you want to be a Java Developer and preparing for the interviews then this question is for you. Most of the time interviewers asked the question to find/count the frequency of the character in a string. By asking these type of questions interviewers are checking your logical ability and how much you know about the Java programming language.

Suppose you have a string like ABACBADDF and you have to count the frequency of each character.

For the string ABACBADDF, the frequency of each character is…

A=3, B=2, C=1, D=2, F=1

Let’s check the complete example.

CountCharFrequency.java
package org.websparrow;

import java.util.HashMap;
import java.util.Map;

public class CountCharFrequency {

	public static void main(String[] args) {
		
		String str = "ABACBADDF";
		Map<Character, Integer> map = new HashMap<>();
		
		for (int i = 0; i < str.length(); i++) {

			char ch = str.charAt(i);
			Integer ctr = map.get(ch);

			if (ctr != null) {
				map.put(ch, new Integer(ctr + 1));
			} else {
				map.put(ch, 1);
			}
		}
		System.out.println(map);
	}
}
Output:

Find the result on your console log.

{A=3, B=2, C=1, D=2, F=1}

Similar Posts

About the Author

Atul Rai
I love sharing my experiments and ideas with everyone by writing articles on the latest technological trends. Read all published posts by Atul Rai.