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.
๐ Master Frequency-Based String Problems in Java
Counting character occurrences is a fundamental technique used in many Java string and coding-round problems. Strengthen your problem-solving skills by exploring these closely related string programs and interview resources.
๐ง Java Coding Round Questions
Practice frequency-based string and HashMap problems.
๐ First Non-Repeated Character
Directly applies character frequency counting logic.
๐งฎ Check Anagram Strings
Uses frequency maps to compare two strings.
๐ Longest Palindromic Substring
Advanced string problem that builds on traversal techniques.
๐ Palindrome String Program
Learn basic palindrome checks before solving complex variants.
๐ Reverse String in Java
Strengthen string traversal fundamentals.
๐ข String Contains Only Digits
Practice validation-focused string processing.
๐ฆ Java Collections Interview Questions
Understand HashMap usage in interview scenarios.
๐ฏ Java Interview Questions (Freshers)
Common interview questions involving strings and collections.
๐งช Advanced Java Programs (Real-World)
Apply frequency-based logic in real-world Java problems.