Java program to find the counts of each character in a String

Java Program to find character counts in a String :

In this tutorial, we will find the count of each characters in a given string (updated version).

Solution :

  1. First get the string input from the user
  2. Create one hashmap with key as ‘character’ and value as ‘integer’ . Count of each character will be stored as value with key as the character.
  3. Scan the string character by character
  4. Check for each character : if no key equalt to the character is available in the hashmap , add one new key as the character and value as 1.
  5. If key is available, increment the value by one.
import java.util.HashMap;
import java.util.Scanner;

public class Main {

    public static void main(String[] args) {
        String line;
        int value;
        Scanner sc = new Scanner(;

        HashMap<Character,Integer> map = new HashMap<Character,Integer>();
        System.out.println("Enter a String :");

        line = sc.nextLine();

        for (int i=0; i<line.length(); i++){
                value = map.get(line.charAt(i));
                value ++;

        for ( Character key : map.keySet()){
            System.out.println("Character : '"+key+"' Count :"+map.get(key));



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 ❤️❤️🤩