Count Character Occurrences in Java

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.