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

Published by admin on

Java 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 :

Categories: java

1 Comment

Seymour · May 11, 2018 at 1:30 am

Good tutorial on counting chars in a String. The commons.lang.StringUtils library has a countMatches() method that would work well in this example.

Leave a Reply

Your email address will not be published. Required fields are marked *