In this post, we'll learn how to count the occurrence of each character in a given string using Java. This is a frequently asked question in Java coding interviews and also helps in mastering Map
data structure.
🧠Why Character Frequency?
It helps in solving many string-related problems such as anagrams, duplicates, and string compression. Understanding how to use a map to count items is a valuable skill.
1️⃣ Count Character Frequency Using HashMap
import java.util.HashMap;
import java.util.Map;
public class CharacterCount {
public static void main(String[] args) {
String input = "hello world";
Map<Character, Integer> countMap = new HashMap<>();
for (char c : input.toCharArray()) {
if (c != ' ') { // skip spaces
countMap.put(c, countMap.getOrDefault(c, 0) + 1);
}
}
for (Map.Entry<Character, Integer> entry : countMap.entrySet()) {
System.out.println(entry.getKey() + ": " + entry.getValue());
}
}
}
✅ Output
h: 1 e: 1 l: 3 o: 2 w: 1 r: 1 d: 1
📌 Interview Tip
This program is often extended to ask for the most frequent character or to ignore case sensitivity. Always clarify requirements before jumping into the code.
📚 Conclusion
Using a HashMap to count character occurrences is a fundamental technique in Java string manipulation. It's efficient and scalable even for large strings.