Java program to count the occurrence of each character in a string

Java program to count the occurrence of each character in a string :

In this tutorial, we will learn how to count the occurrence of each character in a String. The user will enter one string and we will count the occurrence of each character in that string. We will use one HashMap to store the character and count for that character. The key of that hash map is Character and value is Integer. Let’s take a look at the Java program first :

Java program to count each character :

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

public class Main {

    public static void main(String[] args) {
        String inputString;

        Scanner scanner = new Scanner(;

        int count;

        System.out.println("Enter a string : ");

        inputString = scanner.nextLine();

        HashMap<Character, Integer> map = new HashMap<>();

        for (char character : inputString.toCharArray()) {
            if (map.containsKey(character)) {
                count = map.get(character);
                map.put(character, count + 1);
            } else {
                map.put(character, 1);

        for (Map.Entry<Character, Integer> entry : map.entrySet()) {
            System.out.println(entry.getKey() + " : " + entry.getValue());



Explanation :

  1. Create one String variable to store the user input String: inputString.
  2. Create one Scanner object to read user input contents.
  3. Create one integer variable to store the count for each character.
  4. Ask the user to enter a String.
  5. Read the string using Scanner object and store it in the inputString variable.
  6. Create one HashMap. The key of this map is of type Character and value is of type Integer.
  7. Read each character of the string. We are converting the String to an array using toCharArray() method first. This helps us to read each character using a for loop.
  8. Check if the HashMap contains the current character or not. If it contains, gets the value for that character key. Increment it and store it again for that character. If it doesn?t contain, store value as 1 for that character.
  9. After all, characters are scanned, use one for loop to read all character and count for that character. Print out the result to the user.

Sample Output :

Enter a string :
p : 2
A : 1
e : 1
l : 1

Enter a string :
a : 1
b : 1
l : 2

Similar tutorials :

Where is the color and why codevscolor ?

Long story short, I love paintings and I paint on weekends. We(me and my wife) have one Youtube channel. Don't forget to subscribe ❤️❤️🤩