Java Program to Count the Occurrences of Each Character in String

In this blog post, we will write a Java program that counts the occurrences of each character in a given string. This program utilizes data structures and looping constructs to efficiently determine the frequency of each character and display the results. Let's dive into the code and see how it works!

Java Program to Count the Occurrences of Each Character in String

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

public class CharacterCount {
    public static void main(String[] args) {
        String inputString = "Java is a widely used programming language. Java is versatile and has a large community.";

        Map<Character, Integer> characterCountMap = new HashMap<>();

        // Counting character occurrences
        for (char c : inputString.toCharArray()) {
            if (characterCountMap.containsKey(c)) {
                characterCountMap.put(c, characterCountMap.get(c) + 1);
            } else {
                characterCountMap.put(c, 1);

        // Displaying character counts
        for (Map.Entry<Character, Integer> entry : characterCountMap.entrySet()) {
            System.out.println("'" + entry.getKey() + "' : " + entry.getValue());


' ' : 14
'a' : 13
'c' : 1
'd' : 3
'e' : 6
'g' : 5
'h' : 1
'i' : 6
'J' : 2
'l' : 4
'm' : 4
'n' : 4
'.' : 2
'o' : 2
'p' : 1
'r' : 4
's' : 5
't' : 2
'u' : 3
'v' : 3
'w' : 1
'y' : 2


1. The program begins by initializing the inputString variable with the desired text. 

2. A HashMap called characterCountMap is created to store the character frequencies. 

3. The program iterates through each character in the inputString by converting it into a character array using toCharArray()

4. For each character, it checks if it already exists in the characterCountMap. If the character exists, its count is incremented by 1. If the character does not exist, it is added to the characterCountMap with a count of 1. 

5. After counting the occurrences of each character, the program iterates through the characterCountMap

6. For each entry, it displays the character surrounded by single quotes and its corresponding count. 

Note: The program treats each character independently, including spaces, punctuation marks, and special characters. Feel free to modify the inputString variable to test the program with different strings.


Congratulations! You have learned how to write a Java program to count the occurrences of each character in a given string. By utilizing a HashMap and iterating through the characters, we efficiently determine the frequency of each character. This program can be useful in various applications, such as text analysis and data processing. 

Feel free to incorporate this code into your Java projects or customize it to suit your specific requirements. Happy coding!

Related Java String Programs